babylon.max.js 4.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. var BABYLON;
  839. (function (BABYLON) {
  840. var KeyboardEventTypes = /** @class */ (function () {
  841. function KeyboardEventTypes() {
  842. }
  843. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  844. get: function () {
  845. return KeyboardEventTypes._KEYDOWN;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  851. get: function () {
  852. return KeyboardEventTypes._KEYUP;
  853. },
  854. enumerable: true,
  855. configurable: true
  856. });
  857. KeyboardEventTypes._KEYDOWN = 0x01;
  858. KeyboardEventTypes._KEYUP = 0x02;
  859. return KeyboardEventTypes;
  860. }());
  861. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  862. var KeyboardInfo = /** @class */ (function () {
  863. function KeyboardInfo(type, event) {
  864. this.type = type;
  865. this.event = event;
  866. }
  867. return KeyboardInfo;
  868. }());
  869. BABYLON.KeyboardInfo = KeyboardInfo;
  870. /**
  871. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  872. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  873. */
  874. var KeyboardInfoPre = /** @class */ (function (_super) {
  875. __extends(KeyboardInfoPre, _super);
  876. function KeyboardInfoPre(type, event) {
  877. var _this = _super.call(this, type, event) || this;
  878. _this.skipOnPointerObservable = false;
  879. return _this;
  880. }
  881. return KeyboardInfoPre;
  882. }(KeyboardInfo));
  883. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  884. })(BABYLON || (BABYLON = {}));
  885. //# sourceMappingURL=babylon.keyboardEvents.js.map
  886. var BABYLON;
  887. (function (BABYLON) {
  888. var PointerEventTypes = /** @class */ (function () {
  889. function PointerEventTypes() {
  890. }
  891. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  892. get: function () {
  893. return PointerEventTypes._POINTERDOWN;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  899. get: function () {
  900. return PointerEventTypes._POINTERUP;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  906. get: function () {
  907. return PointerEventTypes._POINTERMOVE;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  913. get: function () {
  914. return PointerEventTypes._POINTERWHEEL;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  920. get: function () {
  921. return PointerEventTypes._POINTERPICK;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  927. get: function () {
  928. return PointerEventTypes._POINTERTAP;
  929. },
  930. enumerable: true,
  931. configurable: true
  932. });
  933. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  934. get: function () {
  935. return PointerEventTypes._POINTERDOUBLETAP;
  936. },
  937. enumerable: true,
  938. configurable: true
  939. });
  940. PointerEventTypes._POINTERDOWN = 0x01;
  941. PointerEventTypes._POINTERUP = 0x02;
  942. PointerEventTypes._POINTERMOVE = 0x04;
  943. PointerEventTypes._POINTERWHEEL = 0x08;
  944. PointerEventTypes._POINTERPICK = 0x10;
  945. PointerEventTypes._POINTERTAP = 0x20;
  946. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  947. return PointerEventTypes;
  948. }());
  949. BABYLON.PointerEventTypes = PointerEventTypes;
  950. var PointerInfoBase = /** @class */ (function () {
  951. function PointerInfoBase(type, event) {
  952. this.type = type;
  953. this.event = event;
  954. }
  955. return PointerInfoBase;
  956. }());
  957. BABYLON.PointerInfoBase = PointerInfoBase;
  958. /**
  959. * This class is used to store pointer related info for the onPrePointerObservable event.
  960. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  961. */
  962. var PointerInfoPre = /** @class */ (function (_super) {
  963. __extends(PointerInfoPre, _super);
  964. function PointerInfoPre(type, event, localX, localY) {
  965. var _this = _super.call(this, type, event) || this;
  966. _this.skipOnPointerObservable = false;
  967. _this.localPosition = new BABYLON.Vector2(localX, localY);
  968. return _this;
  969. }
  970. return PointerInfoPre;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfoPre = PointerInfoPre;
  973. /**
  974. * This type contains all the data related to a pointer event in Babylon.js.
  975. * 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.
  976. */
  977. var PointerInfo = /** @class */ (function (_super) {
  978. __extends(PointerInfo, _super);
  979. function PointerInfo(type, event, pickInfo) {
  980. var _this = _super.call(this, type, event) || this;
  981. _this.pickInfo = pickInfo;
  982. return _this;
  983. }
  984. return PointerInfo;
  985. }(PointerInfoBase));
  986. BABYLON.PointerInfo = PointerInfo;
  987. })(BABYLON || (BABYLON = {}));
  988. //# sourceMappingURL=babylon.pointerEvents.js.map
  989. var BABYLON;
  990. (function (BABYLON) {
  991. BABYLON.ToGammaSpace = 1 / 2.2;
  992. BABYLON.ToLinearSpace = 2.2;
  993. BABYLON.Epsilon = 0.001;
  994. var Color3 = /** @class */ (function () {
  995. /**
  996. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  997. */
  998. function Color3(r, g, b) {
  999. if (r === void 0) { r = 0; }
  1000. if (g === void 0) { g = 0; }
  1001. if (b === void 0) { b = 0; }
  1002. this.r = r;
  1003. this.g = g;
  1004. this.b = b;
  1005. }
  1006. /**
  1007. * Returns a string with the Color3 current values.
  1008. */
  1009. Color3.prototype.toString = function () {
  1010. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1011. };
  1012. /**
  1013. * Returns the string "Color3".
  1014. */
  1015. Color3.prototype.getClassName = function () {
  1016. return "Color3";
  1017. };
  1018. /**
  1019. * Returns the Color3 hash code.
  1020. */
  1021. Color3.prototype.getHashCode = function () {
  1022. var hash = this.r || 0;
  1023. hash = (hash * 397) ^ (this.g || 0);
  1024. hash = (hash * 397) ^ (this.b || 0);
  1025. return hash;
  1026. };
  1027. // Operators
  1028. /**
  1029. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1030. * Returns the Color3.
  1031. */
  1032. Color3.prototype.toArray = function (array, index) {
  1033. if (index === undefined) {
  1034. index = 0;
  1035. }
  1036. array[index] = this.r;
  1037. array[index + 1] = this.g;
  1038. array[index + 2] = this.b;
  1039. return this;
  1040. };
  1041. /**
  1042. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1043. */
  1044. Color3.prototype.toColor4 = function (alpha) {
  1045. if (alpha === void 0) { alpha = 1; }
  1046. return new Color4(this.r, this.g, this.b, alpha);
  1047. };
  1048. /**
  1049. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1050. */
  1051. Color3.prototype.asArray = function () {
  1052. var result = new Array();
  1053. this.toArray(result, 0);
  1054. return result;
  1055. };
  1056. /**
  1057. * Returns the luminance value (float).
  1058. */
  1059. Color3.prototype.toLuminance = function () {
  1060. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1061. };
  1062. /**
  1063. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1064. * Returns this new object.
  1065. */
  1066. Color3.prototype.multiply = function (otherColor) {
  1067. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1068. };
  1069. /**
  1070. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1071. * Returns the current Color3.
  1072. */
  1073. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1074. result.r = this.r * otherColor.r;
  1075. result.g = this.g * otherColor.g;
  1076. result.b = this.b * otherColor.b;
  1077. return this;
  1078. };
  1079. /**
  1080. * Boolean : True if the rgb values are equal to the passed ones.
  1081. */
  1082. Color3.prototype.equals = function (otherColor) {
  1083. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1084. };
  1085. /**
  1086. * Boolean : True if the rgb values are equal to the passed ones.
  1087. */
  1088. Color3.prototype.equalsFloats = function (r, g, b) {
  1089. return this.r === r && this.g === g && this.b === b;
  1090. };
  1091. /**
  1092. * Multiplies in place each rgb value by scale.
  1093. * Returns the updated Color3.
  1094. */
  1095. Color3.prototype.scale = function (scale) {
  1096. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1097. };
  1098. /**
  1099. * Multiplies the rgb values by scale and stores the result into "result".
  1100. * Returns the unmodified current Color3.
  1101. */
  1102. Color3.prototype.scaleToRef = function (scale, result) {
  1103. result.r = this.r * scale;
  1104. result.g = this.g * scale;
  1105. result.b = this.b * scale;
  1106. return this;
  1107. };
  1108. /**
  1109. * Clamps the rgb values by the min and max values and stores the result into "result".
  1110. * Returns the unmodified current Color3.
  1111. * @param min - minimum clamping value. Defaults to 0
  1112. * @param max - maximum clamping value. Defaults to 1
  1113. * @param result - color to store the result into.
  1114. * @returns - the original Color3
  1115. */
  1116. Color3.prototype.clampToRef = function (min, max, result) {
  1117. if (min === void 0) { min = 0; }
  1118. if (max === void 0) { max = 1; }
  1119. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1120. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1121. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1122. return this;
  1123. };
  1124. /**
  1125. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1126. */
  1127. Color3.prototype.add = function (otherColor) {
  1128. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1129. };
  1130. /**
  1131. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1132. * Returns the unmodified current Color3.
  1133. */
  1134. Color3.prototype.addToRef = function (otherColor, result) {
  1135. result.r = this.r + otherColor.r;
  1136. result.g = this.g + otherColor.g;
  1137. result.b = this.b + otherColor.b;
  1138. return this;
  1139. };
  1140. /**
  1141. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1142. */
  1143. Color3.prototype.subtract = function (otherColor) {
  1144. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1145. };
  1146. /**
  1147. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1148. * Returns the unmodified current Color3.
  1149. */
  1150. Color3.prototype.subtractToRef = function (otherColor, result) {
  1151. result.r = this.r - otherColor.r;
  1152. result.g = this.g - otherColor.g;
  1153. result.b = this.b - otherColor.b;
  1154. return this;
  1155. };
  1156. /**
  1157. * Returns a new Color3 copied the current one.
  1158. */
  1159. Color3.prototype.clone = function () {
  1160. return new Color3(this.r, this.g, this.b);
  1161. };
  1162. /**
  1163. * Copies the rgb values from the source in the current Color3.
  1164. * Returns the updated Color3.
  1165. */
  1166. Color3.prototype.copyFrom = function (source) {
  1167. this.r = source.r;
  1168. this.g = source.g;
  1169. this.b = source.b;
  1170. return this;
  1171. };
  1172. /**
  1173. * Updates the Color3 rgb values from the passed floats.
  1174. * Returns the Color3.
  1175. */
  1176. Color3.prototype.copyFromFloats = function (r, g, b) {
  1177. this.r = r;
  1178. this.g = g;
  1179. this.b = b;
  1180. return this;
  1181. };
  1182. /**
  1183. * Updates the Color3 rgb values from the passed floats.
  1184. * Returns the Color3.
  1185. */
  1186. Color3.prototype.set = function (r, g, b) {
  1187. return this.copyFromFloats(r, g, b);
  1188. };
  1189. /**
  1190. * Returns the Color3 hexadecimal code as a string.
  1191. */
  1192. Color3.prototype.toHexString = function () {
  1193. var intR = (this.r * 255) | 0;
  1194. var intG = (this.g * 255) | 0;
  1195. var intB = (this.b * 255) | 0;
  1196. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1197. };
  1198. /**
  1199. * Returns a new Color3 converted to linear space.
  1200. */
  1201. Color3.prototype.toLinearSpace = function () {
  1202. var convertedColor = new Color3();
  1203. this.toLinearSpaceToRef(convertedColor);
  1204. return convertedColor;
  1205. };
  1206. /**
  1207. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1208. * Returns the unmodified Color3.
  1209. */
  1210. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1211. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1212. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1213. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Color3 converted to gamma space.
  1218. */
  1219. Color3.prototype.toGammaSpace = function () {
  1220. var convertedColor = new Color3();
  1221. this.toGammaSpaceToRef(convertedColor);
  1222. return convertedColor;
  1223. };
  1224. /**
  1225. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1226. * Returns the unmodified Color3.
  1227. */
  1228. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1229. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1230. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1231. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1232. return this;
  1233. };
  1234. // Statics
  1235. /**
  1236. * Creates a new Color3 from the string containing valid hexadecimal values.
  1237. */
  1238. Color3.FromHexString = function (hex) {
  1239. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1240. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1241. return new Color3(0, 0, 0);
  1242. }
  1243. var r = parseInt(hex.substring(1, 3), 16);
  1244. var g = parseInt(hex.substring(3, 5), 16);
  1245. var b = parseInt(hex.substring(5, 7), 16);
  1246. return Color3.FromInts(r, g, b);
  1247. };
  1248. /**
  1249. * Creates a new Vector3 from the startind index of the passed array.
  1250. */
  1251. Color3.FromArray = function (array, offset) {
  1252. if (offset === void 0) { offset = 0; }
  1253. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1254. };
  1255. /**
  1256. * Creates a new Color3 from integer values ( < 256).
  1257. */
  1258. Color3.FromInts = function (r, g, b) {
  1259. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1260. };
  1261. /**
  1262. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1263. */
  1264. Color3.Lerp = function (start, end, amount) {
  1265. var r = start.r + ((end.r - start.r) * amount);
  1266. var g = start.g + ((end.g - start.g) * amount);
  1267. var b = start.b + ((end.b - start.b) * amount);
  1268. return new Color3(r, g, b);
  1269. };
  1270. Color3.Red = function () { return new Color3(1, 0, 0); };
  1271. Color3.Green = function () { return new Color3(0, 1, 0); };
  1272. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1273. Color3.Black = function () { return new Color3(0, 0, 0); };
  1274. Color3.White = function () { return new Color3(1, 1, 1); };
  1275. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1276. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1277. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1278. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1279. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1280. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1281. return Color3;
  1282. }());
  1283. BABYLON.Color3 = Color3;
  1284. var Color4 = /** @class */ (function () {
  1285. /**
  1286. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1287. */
  1288. function Color4(r, g, b, a) {
  1289. if (r === void 0) { r = 0; }
  1290. if (g === void 0) { g = 0; }
  1291. if (b === void 0) { b = 0; }
  1292. if (a === void 0) { a = 1; }
  1293. this.r = r;
  1294. this.g = g;
  1295. this.b = b;
  1296. this.a = a;
  1297. }
  1298. // Operators
  1299. /**
  1300. * Adds in place the passed Color4 values to the current Color4.
  1301. * Returns the updated Color4.
  1302. */
  1303. Color4.prototype.addInPlace = function (right) {
  1304. this.r += right.r;
  1305. this.g += right.g;
  1306. this.b += right.b;
  1307. this.a += right.a;
  1308. return this;
  1309. };
  1310. /**
  1311. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1312. */
  1313. Color4.prototype.asArray = function () {
  1314. var result = new Array();
  1315. this.toArray(result, 0);
  1316. return result;
  1317. };
  1318. /**
  1319. * Stores from the starting index in the passed array the Color4 successive values.
  1320. * Returns the Color4.
  1321. */
  1322. Color4.prototype.toArray = function (array, index) {
  1323. if (index === undefined) {
  1324. index = 0;
  1325. }
  1326. array[index] = this.r;
  1327. array[index + 1] = this.g;
  1328. array[index + 2] = this.b;
  1329. array[index + 3] = this.a;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1334. */
  1335. Color4.prototype.add = function (right) {
  1336. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1337. };
  1338. /**
  1339. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1340. */
  1341. Color4.prototype.subtract = function (right) {
  1342. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1343. };
  1344. /**
  1345. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1346. * Returns the Color4.
  1347. */
  1348. Color4.prototype.subtractToRef = function (right, result) {
  1349. result.r = this.r - right.r;
  1350. result.g = this.g - right.g;
  1351. result.b = this.b - right.b;
  1352. result.a = this.a - right.a;
  1353. return this;
  1354. };
  1355. /**
  1356. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1357. */
  1358. Color4.prototype.scale = function (scale) {
  1359. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1360. };
  1361. /**
  1362. * Multiplies the current Color4 values by scale and stores the result in "result".
  1363. * Returns the Color4.
  1364. */
  1365. Color4.prototype.scaleToRef = function (scale, result) {
  1366. result.r = this.r * scale;
  1367. result.g = this.g * scale;
  1368. result.b = this.b * scale;
  1369. result.a = this.a * scale;
  1370. return this;
  1371. };
  1372. /**
  1373. * Clamps the rgb values by the min and max values and stores the result into "result".
  1374. * Returns the unmodified current Color4.
  1375. * @param min - minimum clamping value. Defaults to 0
  1376. * @param max - maximum clamping value. Defaults to 1
  1377. * @param result - color to store the result into.
  1378. * @returns - the original Color4
  1379. */
  1380. Color4.prototype.clampToRef = function (min, max, result) {
  1381. if (min === void 0) { min = 0; }
  1382. if (max === void 0) { max = 1; }
  1383. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1384. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1385. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1386. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1387. return this;
  1388. };
  1389. /**
  1390. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1391. * @param color The Color4 (RGBA) value to multiply by
  1392. * @returns A new Color4.
  1393. */
  1394. Color4.prototype.multiply = function (color) {
  1395. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1396. };
  1397. /**
  1398. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1399. * @param color The Color4 (RGBA) value to multiply by
  1400. * @param result The Color4 (RGBA) to fill the result in
  1401. * @returns the result Color4.
  1402. */
  1403. Color4.prototype.multiplyToRef = function (color, result) {
  1404. result.r = this.r * color.r;
  1405. result.g = this.g * color.g;
  1406. result.b = this.b * color.b;
  1407. result.a = this.a * color.a;
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns a string with the Color4 values.
  1412. */
  1413. Color4.prototype.toString = function () {
  1414. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1415. };
  1416. /**
  1417. * Returns the string "Color4"
  1418. */
  1419. Color4.prototype.getClassName = function () {
  1420. return "Color4";
  1421. };
  1422. /**
  1423. * Return the Color4 hash code as a number.
  1424. */
  1425. Color4.prototype.getHashCode = function () {
  1426. var hash = this.r || 0;
  1427. hash = (hash * 397) ^ (this.g || 0);
  1428. hash = (hash * 397) ^ (this.b || 0);
  1429. hash = (hash * 397) ^ (this.a || 0);
  1430. return hash;
  1431. };
  1432. /**
  1433. * Creates a new Color4 copied from the current one.
  1434. */
  1435. Color4.prototype.clone = function () {
  1436. return new Color4(this.r, this.g, this.b, this.a);
  1437. };
  1438. /**
  1439. * Copies the passed Color4 values into the current one.
  1440. * Returns the updated Color4.
  1441. */
  1442. Color4.prototype.copyFrom = function (source) {
  1443. this.r = source.r;
  1444. this.g = source.g;
  1445. this.b = source.b;
  1446. this.a = source.a;
  1447. return this;
  1448. };
  1449. /**
  1450. * Copies the passed float values into the current one.
  1451. * Returns the updated Color4.
  1452. */
  1453. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1454. this.r = r;
  1455. this.g = g;
  1456. this.b = b;
  1457. this.a = a;
  1458. return this;
  1459. };
  1460. /**
  1461. * Copies the passed float values into the current one.
  1462. * Returns the updated Color4.
  1463. */
  1464. Color4.prototype.set = function (r, g, b, a) {
  1465. return this.copyFromFloats(r, g, b, a);
  1466. };
  1467. /**
  1468. * Returns a string containing the hexadecimal Color4 code.
  1469. */
  1470. Color4.prototype.toHexString = function () {
  1471. var intR = (this.r * 255) | 0;
  1472. var intG = (this.g * 255) | 0;
  1473. var intB = (this.b * 255) | 0;
  1474. var intA = (this.a * 255) | 0;
  1475. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1476. };
  1477. /**
  1478. * Returns a new Color4 converted to linear space.
  1479. */
  1480. Color4.prototype.toLinearSpace = function () {
  1481. var convertedColor = new Color4();
  1482. this.toLinearSpaceToRef(convertedColor);
  1483. return convertedColor;
  1484. };
  1485. /**
  1486. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1487. * Returns the unmodified Color4.
  1488. */
  1489. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1490. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1491. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1492. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1493. convertedColor.a = this.a;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new Color4 converted to gamma space.
  1498. */
  1499. Color4.prototype.toGammaSpace = function () {
  1500. var convertedColor = new Color4();
  1501. this.toGammaSpaceToRef(convertedColor);
  1502. return convertedColor;
  1503. };
  1504. /**
  1505. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1506. * Returns the unmodified Color4.
  1507. */
  1508. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1509. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1510. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1511. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1512. convertedColor.a = this.a;
  1513. return this;
  1514. };
  1515. // Statics
  1516. /**
  1517. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1518. */
  1519. Color4.FromHexString = function (hex) {
  1520. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1521. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1522. return new Color4(0.0, 0.0, 0.0, 0.0);
  1523. }
  1524. var r = parseInt(hex.substring(1, 3), 16);
  1525. var g = parseInt(hex.substring(3, 5), 16);
  1526. var b = parseInt(hex.substring(5, 7), 16);
  1527. var a = parseInt(hex.substring(7, 9), 16);
  1528. return Color4.FromInts(r, g, b, a);
  1529. };
  1530. /**
  1531. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1532. */
  1533. Color4.Lerp = function (left, right, amount) {
  1534. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1535. Color4.LerpToRef(left, right, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1540. */
  1541. Color4.LerpToRef = function (left, right, amount, result) {
  1542. result.r = left.r + (right.r - left.r) * amount;
  1543. result.g = left.g + (right.g - left.g) * amount;
  1544. result.b = left.b + (right.b - left.b) * amount;
  1545. result.a = left.a + (right.a - left.a) * amount;
  1546. };
  1547. /**
  1548. * Creates a new Color4 from the starting index element of the passed array.
  1549. */
  1550. Color4.FromArray = function (array, offset) {
  1551. if (offset === void 0) { offset = 0; }
  1552. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1553. };
  1554. /**
  1555. * Creates a new Color4 from the passed integers ( < 256 ).
  1556. */
  1557. Color4.FromInts = function (r, g, b, a) {
  1558. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1559. };
  1560. Color4.CheckColors4 = function (colors, count) {
  1561. // Check if color3 was used
  1562. if (colors.length === count * 3) {
  1563. var colors4 = [];
  1564. for (var index = 0; index < colors.length; index += 3) {
  1565. var newIndex = (index / 3) * 4;
  1566. colors4[newIndex] = colors[index];
  1567. colors4[newIndex + 1] = colors[index + 1];
  1568. colors4[newIndex + 2] = colors[index + 2];
  1569. colors4[newIndex + 3] = 1.0;
  1570. }
  1571. return colors4;
  1572. }
  1573. return colors;
  1574. };
  1575. return Color4;
  1576. }());
  1577. BABYLON.Color4 = Color4;
  1578. var Vector2 = /** @class */ (function () {
  1579. /**
  1580. * Creates a new Vector2 from the passed x and y coordinates.
  1581. */
  1582. function Vector2(x, y) {
  1583. this.x = x;
  1584. this.y = y;
  1585. }
  1586. /**
  1587. * Returns a string with the Vector2 coordinates.
  1588. */
  1589. Vector2.prototype.toString = function () {
  1590. return "{X: " + this.x + " Y:" + this.y + "}";
  1591. };
  1592. /**
  1593. * Returns the string "Vector2"
  1594. */
  1595. Vector2.prototype.getClassName = function () {
  1596. return "Vector2";
  1597. };
  1598. /**
  1599. * Returns the Vector2 hash code as a number.
  1600. */
  1601. Vector2.prototype.getHashCode = function () {
  1602. var hash = this.x || 0;
  1603. hash = (hash * 397) ^ (this.y || 0);
  1604. return hash;
  1605. };
  1606. // Operators
  1607. /**
  1608. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1609. * Returns the Vector2.
  1610. */
  1611. Vector2.prototype.toArray = function (array, index) {
  1612. if (index === void 0) { index = 0; }
  1613. array[index] = this.x;
  1614. array[index + 1] = this.y;
  1615. return this;
  1616. };
  1617. /**
  1618. * Returns a new array with 2 elements : the Vector2 coordinates.
  1619. */
  1620. Vector2.prototype.asArray = function () {
  1621. var result = new Array();
  1622. this.toArray(result, 0);
  1623. return result;
  1624. };
  1625. /**
  1626. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1627. * Returns the updated Vector2.
  1628. */
  1629. Vector2.prototype.copyFrom = function (source) {
  1630. this.x = source.x;
  1631. this.y = source.y;
  1632. return this;
  1633. };
  1634. /**
  1635. * Sets the Vector2 coordinates with the passed floats.
  1636. * Returns the updated Vector2.
  1637. */
  1638. Vector2.prototype.copyFromFloats = function (x, y) {
  1639. this.x = x;
  1640. this.y = y;
  1641. return this;
  1642. };
  1643. /**
  1644. * Sets the Vector2 coordinates with the passed floats.
  1645. * Returns the updated Vector2.
  1646. */
  1647. Vector2.prototype.set = function (x, y) {
  1648. return this.copyFromFloats(x, y);
  1649. };
  1650. /**
  1651. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1652. */
  1653. Vector2.prototype.add = function (otherVector) {
  1654. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1655. };
  1656. /**
  1657. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1658. * Returns the Vector2.
  1659. */
  1660. Vector2.prototype.addToRef = function (otherVector, result) {
  1661. result.x = this.x + otherVector.x;
  1662. result.y = this.y + otherVector.y;
  1663. return this;
  1664. };
  1665. /**
  1666. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1667. * Returns the updated Vector2.
  1668. */
  1669. Vector2.prototype.addInPlace = function (otherVector) {
  1670. this.x += otherVector.x;
  1671. this.y += otherVector.y;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1676. */
  1677. Vector2.prototype.addVector3 = function (otherVector) {
  1678. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1679. };
  1680. /**
  1681. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1682. */
  1683. Vector2.prototype.subtract = function (otherVector) {
  1684. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1685. };
  1686. /**
  1687. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1688. * Returns the Vector2.
  1689. */
  1690. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1691. result.x = this.x - otherVector.x;
  1692. result.y = this.y - otherVector.y;
  1693. return this;
  1694. };
  1695. /**
  1696. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1697. * Returns the updated Vector2.
  1698. */
  1699. Vector2.prototype.subtractInPlace = function (otherVector) {
  1700. this.x -= otherVector.x;
  1701. this.y -= otherVector.y;
  1702. return this;
  1703. };
  1704. /**
  1705. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1706. * Returns the updated Vector2.
  1707. */
  1708. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1709. this.x *= otherVector.x;
  1710. this.y *= otherVector.y;
  1711. return this;
  1712. };
  1713. /**
  1714. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1715. */
  1716. Vector2.prototype.multiply = function (otherVector) {
  1717. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1718. };
  1719. /**
  1720. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1721. * Returns the Vector2.
  1722. */
  1723. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1724. result.x = this.x * otherVector.x;
  1725. result.y = this.y * otherVector.y;
  1726. return this;
  1727. };
  1728. /**
  1729. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1730. */
  1731. Vector2.prototype.multiplyByFloats = function (x, y) {
  1732. return new Vector2(this.x * x, this.y * y);
  1733. };
  1734. /**
  1735. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1736. */
  1737. Vector2.prototype.divide = function (otherVector) {
  1738. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1739. };
  1740. /**
  1741. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1742. * Returns the Vector2.
  1743. */
  1744. Vector2.prototype.divideToRef = function (otherVector, result) {
  1745. result.x = this.x / otherVector.x;
  1746. result.y = this.y / otherVector.y;
  1747. return this;
  1748. };
  1749. /**
  1750. * Divides the current Vector3 coordinates by the passed ones.
  1751. * Returns the updated Vector3.
  1752. */
  1753. Vector2.prototype.divideInPlace = function (otherVector) {
  1754. return this.divideToRef(otherVector, this);
  1755. };
  1756. /**
  1757. * Returns a new Vector2 with current Vector2 negated coordinates.
  1758. */
  1759. Vector2.prototype.negate = function () {
  1760. return new Vector2(-this.x, -this.y);
  1761. };
  1762. /**
  1763. * Multiply the Vector2 coordinates by scale.
  1764. * Returns the updated Vector2.
  1765. */
  1766. Vector2.prototype.scaleInPlace = function (scale) {
  1767. this.x *= scale;
  1768. this.y *= scale;
  1769. return this;
  1770. };
  1771. /**
  1772. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1773. */
  1774. Vector2.prototype.scale = function (scale) {
  1775. return new Vector2(this.x * scale, this.y * scale);
  1776. };
  1777. /**
  1778. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1779. */
  1780. Vector2.prototype.equals = function (otherVector) {
  1781. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1782. };
  1783. /**
  1784. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1785. */
  1786. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1787. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1788. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1789. };
  1790. // Properties
  1791. /**
  1792. * Returns the vector length (float).
  1793. */
  1794. Vector2.prototype.length = function () {
  1795. return Math.sqrt(this.x * this.x + this.y * this.y);
  1796. };
  1797. /**
  1798. * Returns the vector squared length (float);
  1799. */
  1800. Vector2.prototype.lengthSquared = function () {
  1801. return (this.x * this.x + this.y * this.y);
  1802. };
  1803. // Methods
  1804. /**
  1805. * Normalize the vector.
  1806. * Returns the updated Vector2.
  1807. */
  1808. Vector2.prototype.normalize = function () {
  1809. var len = this.length();
  1810. if (len === 0)
  1811. return this;
  1812. var num = 1.0 / len;
  1813. this.x *= num;
  1814. this.y *= num;
  1815. return this;
  1816. };
  1817. /**
  1818. * Returns a new Vector2 copied from the Vector2.
  1819. */
  1820. Vector2.prototype.clone = function () {
  1821. return new Vector2(this.x, this.y);
  1822. };
  1823. // Statics
  1824. /**
  1825. * Returns a new Vector2(0, 0)
  1826. */
  1827. Vector2.Zero = function () {
  1828. return new Vector2(0, 0);
  1829. };
  1830. /**
  1831. * Returns a new Vector2(1, 1)
  1832. */
  1833. Vector2.One = function () {
  1834. return new Vector2(1, 1);
  1835. };
  1836. /**
  1837. * Returns a new Vector2 set from the passed index element of the passed array.
  1838. */
  1839. Vector2.FromArray = function (array, offset) {
  1840. if (offset === void 0) { offset = 0; }
  1841. return new Vector2(array[offset], array[offset + 1]);
  1842. };
  1843. /**
  1844. * Sets "result" from the passed index element of the passed array.
  1845. */
  1846. Vector2.FromArrayToRef = function (array, offset, result) {
  1847. result.x = array[offset];
  1848. result.y = array[offset + 1];
  1849. };
  1850. /**
  1851. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1852. */
  1853. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1854. var squared = amount * amount;
  1855. var cubed = amount * squared;
  1856. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1857. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1858. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1859. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1860. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1861. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1862. return new Vector2(x, y);
  1863. };
  1864. /**
  1865. * 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".
  1866. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1867. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1868. */
  1869. Vector2.Clamp = function (value, min, max) {
  1870. var x = value.x;
  1871. x = (x > max.x) ? max.x : x;
  1872. x = (x < min.x) ? min.x : x;
  1873. var y = value.y;
  1874. y = (y > max.y) ? max.y : y;
  1875. y = (y < min.y) ? min.y : y;
  1876. return new Vector2(x, y);
  1877. };
  1878. /**
  1879. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1880. */
  1881. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1882. var squared = amount * amount;
  1883. var cubed = amount * squared;
  1884. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1885. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1886. var part3 = (cubed - (2.0 * squared)) + amount;
  1887. var part4 = cubed - squared;
  1888. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1889. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1890. return new Vector2(x, y);
  1891. };
  1892. /**
  1893. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1894. */
  1895. Vector2.Lerp = function (start, end, amount) {
  1896. var x = start.x + ((end.x - start.x) * amount);
  1897. var y = start.y + ((end.y - start.y) * amount);
  1898. return new Vector2(x, y);
  1899. };
  1900. /**
  1901. * Returns the dot product (float) of the vector "left" and the vector "right".
  1902. */
  1903. Vector2.Dot = function (left, right) {
  1904. return left.x * right.x + left.y * right.y;
  1905. };
  1906. /**
  1907. * Returns a new Vector2 equal to the normalized passed vector.
  1908. */
  1909. Vector2.Normalize = function (vector) {
  1910. var newVector = vector.clone();
  1911. newVector.normalize();
  1912. return newVector;
  1913. };
  1914. /**
  1915. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1916. */
  1917. Vector2.Minimize = function (left, right) {
  1918. var x = (left.x < right.x) ? left.x : right.x;
  1919. var y = (left.y < right.y) ? left.y : right.y;
  1920. return new Vector2(x, y);
  1921. };
  1922. /**
  1923. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1924. */
  1925. Vector2.Maximize = function (left, right) {
  1926. var x = (left.x > right.x) ? left.x : right.x;
  1927. var y = (left.y > right.y) ? left.y : right.y;
  1928. return new Vector2(x, y);
  1929. };
  1930. /**
  1931. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1932. */
  1933. Vector2.Transform = function (vector, transformation) {
  1934. var r = Vector2.Zero();
  1935. Vector2.TransformToRef(vector, transformation, r);
  1936. return r;
  1937. };
  1938. /**
  1939. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1940. */
  1941. Vector2.TransformToRef = function (vector, transformation, result) {
  1942. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1943. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1944. result.x = x;
  1945. result.y = y;
  1946. };
  1947. /**
  1948. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1949. */
  1950. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1951. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1952. var sign = a < 0 ? -1 : 1;
  1953. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1954. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1955. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1956. };
  1957. /**
  1958. * Returns the distance (float) between the vectors "value1" and "value2".
  1959. */
  1960. Vector2.Distance = function (value1, value2) {
  1961. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1962. };
  1963. /**
  1964. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1965. */
  1966. Vector2.DistanceSquared = function (value1, value2) {
  1967. var x = value1.x - value2.x;
  1968. var y = value1.y - value2.y;
  1969. return (x * x) + (y * y);
  1970. };
  1971. /**
  1972. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1973. */
  1974. Vector2.Center = function (value1, value2) {
  1975. var center = value1.add(value2);
  1976. center.scaleInPlace(0.5);
  1977. return center;
  1978. };
  1979. /**
  1980. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1981. */
  1982. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1983. var l2 = Vector2.DistanceSquared(segA, segB);
  1984. if (l2 === 0.0) {
  1985. return Vector2.Distance(p, segA);
  1986. }
  1987. var v = segB.subtract(segA);
  1988. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1989. var proj = segA.add(v.multiplyByFloats(t, t));
  1990. return Vector2.Distance(p, proj);
  1991. };
  1992. return Vector2;
  1993. }());
  1994. BABYLON.Vector2 = Vector2;
  1995. var Vector3 = /** @class */ (function () {
  1996. /**
  1997. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1998. * A Vector3 is the main object used in 3D geometry.
  1999. * It can represent etiher the coordinates of a point the space, either a direction.
  2000. */
  2001. function Vector3(x, y, z) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. }
  2006. /**
  2007. * Returns a string with the Vector3 coordinates.
  2008. */
  2009. Vector3.prototype.toString = function () {
  2010. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2011. };
  2012. /**
  2013. * Returns the string "Vector3"
  2014. */
  2015. Vector3.prototype.getClassName = function () {
  2016. return "Vector3";
  2017. };
  2018. /**
  2019. * Returns the Vector hash code.
  2020. */
  2021. Vector3.prototype.getHashCode = function () {
  2022. var hash = this.x || 0;
  2023. hash = (hash * 397) ^ (this.y || 0);
  2024. hash = (hash * 397) ^ (this.z || 0);
  2025. return hash;
  2026. };
  2027. // Operators
  2028. /**
  2029. * Returns a new array with three elements : the coordinates the Vector3.
  2030. */
  2031. Vector3.prototype.asArray = function () {
  2032. var result = [];
  2033. this.toArray(result, 0);
  2034. return result;
  2035. };
  2036. /**
  2037. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2038. * Returns the Vector3.
  2039. */
  2040. Vector3.prototype.toArray = function (array, index) {
  2041. if (index === void 0) { index = 0; }
  2042. array[index] = this.x;
  2043. array[index + 1] = this.y;
  2044. array[index + 2] = this.z;
  2045. return this;
  2046. };
  2047. /**
  2048. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2049. */
  2050. Vector3.prototype.toQuaternion = function () {
  2051. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2052. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2053. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2054. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2055. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2056. var cosy = Math.cos(this.y * 0.5);
  2057. var siny = Math.sin(this.y * 0.5);
  2058. result.x = coszMinusx * siny;
  2059. result.y = -sinzMinusx * siny;
  2060. result.z = sinxPlusz * cosy;
  2061. result.w = cosxPlusz * cosy;
  2062. return result;
  2063. };
  2064. /**
  2065. * Adds the passed vector to the current Vector3.
  2066. * Returns the updated Vector3.
  2067. */
  2068. Vector3.prototype.addInPlace = function (otherVector) {
  2069. this.x += otherVector.x;
  2070. this.y += otherVector.y;
  2071. this.z += otherVector.z;
  2072. return this;
  2073. };
  2074. /**
  2075. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2076. */
  2077. Vector3.prototype.add = function (otherVector) {
  2078. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2079. };
  2080. /**
  2081. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2082. * Returns the current Vector3.
  2083. */
  2084. Vector3.prototype.addToRef = function (otherVector, result) {
  2085. result.x = this.x + otherVector.x;
  2086. result.y = this.y + otherVector.y;
  2087. result.z = this.z + otherVector.z;
  2088. return this;
  2089. };
  2090. /**
  2091. * Subtract the passed vector from the current Vector3.
  2092. * Returns the updated Vector3.
  2093. */
  2094. Vector3.prototype.subtractInPlace = function (otherVector) {
  2095. this.x -= otherVector.x;
  2096. this.y -= otherVector.y;
  2097. this.z -= otherVector.z;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2102. */
  2103. Vector3.prototype.subtract = function (otherVector) {
  2104. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2105. };
  2106. /**
  2107. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2108. * Returns the current Vector3.
  2109. */
  2110. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2111. result.x = this.x - otherVector.x;
  2112. result.y = this.y - otherVector.y;
  2113. result.z = this.z - otherVector.z;
  2114. return this;
  2115. };
  2116. /**
  2117. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2118. */
  2119. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2120. return new Vector3(this.x - x, this.y - y, this.z - z);
  2121. };
  2122. /**
  2123. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2124. * Returns the current Vector3.
  2125. */
  2126. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2127. result.x = this.x - x;
  2128. result.y = this.y - y;
  2129. result.z = this.z - z;
  2130. return this;
  2131. };
  2132. /**
  2133. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2134. */
  2135. Vector3.prototype.negate = function () {
  2136. return new Vector3(-this.x, -this.y, -this.z);
  2137. };
  2138. /**
  2139. * Multiplies the Vector3 coordinates by the float "scale".
  2140. * Returns the updated Vector3.
  2141. */
  2142. Vector3.prototype.scaleInPlace = function (scale) {
  2143. this.x *= scale;
  2144. this.y *= scale;
  2145. this.z *= scale;
  2146. return this;
  2147. };
  2148. /**
  2149. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2150. */
  2151. Vector3.prototype.scale = function (scale) {
  2152. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2153. };
  2154. /**
  2155. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2156. * Returns the current Vector3.
  2157. */
  2158. Vector3.prototype.scaleToRef = function (scale, result) {
  2159. result.x = this.x * scale;
  2160. result.y = this.y * scale;
  2161. result.z = this.z * scale;
  2162. return this;
  2163. };
  2164. /**
  2165. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2166. */
  2167. Vector3.prototype.equals = function (otherVector) {
  2168. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2169. };
  2170. /**
  2171. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2172. */
  2173. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2174. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2175. 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);
  2176. };
  2177. /**
  2178. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2179. */
  2180. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2181. return this.x === x && this.y === y && this.z === z;
  2182. };
  2183. /**
  2184. * Muliplies the current Vector3 coordinates by the passed ones.
  2185. * Returns the updated Vector3.
  2186. */
  2187. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2188. this.x *= otherVector.x;
  2189. this.y *= otherVector.y;
  2190. this.z *= otherVector.z;
  2191. return this;
  2192. };
  2193. /**
  2194. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2195. */
  2196. Vector3.prototype.multiply = function (otherVector) {
  2197. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2198. };
  2199. /**
  2200. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2201. * Returns the current Vector3.
  2202. */
  2203. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2204. result.x = this.x * otherVector.x;
  2205. result.y = this.y * otherVector.y;
  2206. result.z = this.z * otherVector.z;
  2207. return this;
  2208. };
  2209. /**
  2210. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2211. */
  2212. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2213. return new Vector3(this.x * x, this.y * y, this.z * z);
  2214. };
  2215. /**
  2216. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2217. */
  2218. Vector3.prototype.divide = function (otherVector) {
  2219. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2220. };
  2221. /**
  2222. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2223. * Returns the current Vector3.
  2224. */
  2225. Vector3.prototype.divideToRef = function (otherVector, result) {
  2226. result.x = this.x / otherVector.x;
  2227. result.y = this.y / otherVector.y;
  2228. result.z = this.z / otherVector.z;
  2229. return this;
  2230. };
  2231. /**
  2232. * Divides the current Vector3 coordinates by the passed ones.
  2233. * Returns the updated Vector3.
  2234. */
  2235. Vector3.prototype.divideInPlace = function (otherVector) {
  2236. return this.divideToRef(otherVector, this);
  2237. };
  2238. /**
  2239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2240. * Returns the updated Vector3.
  2241. */
  2242. Vector3.prototype.MinimizeInPlace = function (other) {
  2243. if (other.x < this.x)
  2244. this.x = other.x;
  2245. if (other.y < this.y)
  2246. this.y = other.y;
  2247. if (other.z < this.z)
  2248. this.z = other.z;
  2249. return this;
  2250. };
  2251. /**
  2252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2253. * Returns the updated Vector3.
  2254. */
  2255. Vector3.prototype.MaximizeInPlace = function (other) {
  2256. if (other.x > this.x)
  2257. this.x = other.x;
  2258. if (other.y > this.y)
  2259. this.y = other.y;
  2260. if (other.z > this.z)
  2261. this.z = other.z;
  2262. return this;
  2263. };
  2264. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2265. /**
  2266. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2267. */
  2268. get: function () {
  2269. var absX = Math.abs(this.x);
  2270. var absY = Math.abs(this.y);
  2271. if (absX !== absY) {
  2272. return true;
  2273. }
  2274. var absZ = Math.abs(this.z);
  2275. if (absX !== absZ) {
  2276. return true;
  2277. }
  2278. if (absY !== absZ) {
  2279. return true;
  2280. }
  2281. return false;
  2282. },
  2283. enumerable: true,
  2284. configurable: true
  2285. });
  2286. // Properties
  2287. /**
  2288. * Returns the length of the Vector3 (float).
  2289. */
  2290. Vector3.prototype.length = function () {
  2291. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2292. };
  2293. /**
  2294. * Returns the squared length of the Vector3 (float).
  2295. */
  2296. Vector3.prototype.lengthSquared = function () {
  2297. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2298. };
  2299. /**
  2300. * Normalize the current Vector3.
  2301. * Returns the updated Vector3.
  2302. * /!\ In place operation.
  2303. */
  2304. Vector3.prototype.normalize = function () {
  2305. var len = this.length();
  2306. if (len === 0 || len === 1.0)
  2307. return this;
  2308. var num = 1.0 / len;
  2309. this.x *= num;
  2310. this.y *= num;
  2311. this.z *= num;
  2312. return this;
  2313. };
  2314. /**
  2315. * Normalize the current Vector3 to a new vector.
  2316. * @returns the new Vector3.
  2317. */
  2318. Vector3.prototype.normalizeToNew = function () {
  2319. var normalized = new Vector3(0, 0, 0);
  2320. this.normalizeToRef(normalized);
  2321. return normalized;
  2322. };
  2323. /**
  2324. * Normalize the current Vector3 to the reference.
  2325. * @param the reference to update.
  2326. * @returns the updated Vector3.
  2327. */
  2328. Vector3.prototype.normalizeToRef = function (reference) {
  2329. var len = this.length();
  2330. if (len === 0 || len === 1.0) {
  2331. reference.set(this.x, this.y, this.z);
  2332. return reference;
  2333. }
  2334. var scale = 1.0 / len;
  2335. this.scaleToRef(scale, reference);
  2336. return reference;
  2337. };
  2338. /**
  2339. * Returns a new Vector3 copied from the current Vector3.
  2340. */
  2341. Vector3.prototype.clone = function () {
  2342. return new Vector3(this.x, this.y, this.z);
  2343. };
  2344. /**
  2345. * Copies the passed vector coordinates to the current Vector3 ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector3.prototype.copyFrom = function (source) {
  2349. this.x = source.x;
  2350. this.y = source.y;
  2351. this.z = source.z;
  2352. return this;
  2353. };
  2354. /**
  2355. * Copies the passed floats to the current Vector3 coordinates.
  2356. * Returns the updated Vector3.
  2357. */
  2358. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2359. this.x = x;
  2360. this.y = y;
  2361. this.z = z;
  2362. return this;
  2363. };
  2364. /**
  2365. * Copies the passed floats to the current Vector3 coordinates.
  2366. * Returns the updated Vector3.
  2367. */
  2368. Vector3.prototype.set = function (x, y, z) {
  2369. return this.copyFromFloats(x, y, z);
  2370. };
  2371. // Statics
  2372. /**
  2373. *
  2374. */
  2375. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2376. var d0 = Vector3.Dot(vector0, axis) - size;
  2377. var d1 = Vector3.Dot(vector1, axis) - size;
  2378. var s = d0 / (d0 - d1);
  2379. return s;
  2380. };
  2381. /**
  2382. * Get angle between two vectors.
  2383. * @param vector0 angle between vector0 and vector1
  2384. * @param vector1 angle between vector0 and vector1
  2385. * @param normal direction of the normal.
  2386. * @return the angle between vector0 and vector1.
  2387. */
  2388. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2389. var v0 = vector0.clone().normalize();
  2390. var v1 = vector1.clone().normalize();
  2391. var dot = Vector3.Dot(v0, v1);
  2392. var n = Vector3.Cross(v0, v1);
  2393. if (Vector3.Dot(n, normal) > 0) {
  2394. return Math.acos(dot);
  2395. }
  2396. return -Math.acos(dot);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set from the index "offset" of the passed array.
  2400. */
  2401. Vector3.FromArray = function (array, offset) {
  2402. if (!offset) {
  2403. offset = 0;
  2404. }
  2405. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2406. };
  2407. /**
  2408. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2409. * This function is deprecated. Use FromArray instead.
  2410. */
  2411. Vector3.FromFloatArray = function (array, offset) {
  2412. return Vector3.FromArray(array, offset);
  2413. };
  2414. /**
  2415. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2416. */
  2417. Vector3.FromArrayToRef = function (array, offset, result) {
  2418. result.x = array[offset];
  2419. result.y = array[offset + 1];
  2420. result.z = array[offset + 2];
  2421. };
  2422. /**
  2423. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2424. * This function is deprecated. Use FromArrayToRef instead.
  2425. */
  2426. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2427. return Vector3.FromArrayToRef(array, offset, result);
  2428. };
  2429. /**
  2430. * Sets the passed vector "result" with the passed floats.
  2431. */
  2432. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2433. result.x = x;
  2434. result.y = y;
  2435. result.z = z;
  2436. };
  2437. /**
  2438. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2439. */
  2440. Vector3.Zero = function () {
  2441. return new Vector3(0.0, 0.0, 0.0);
  2442. };
  2443. /**
  2444. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2445. */
  2446. Vector3.One = function () {
  2447. return new Vector3(1.0, 1.0, 1.0);
  2448. };
  2449. /**
  2450. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2451. */
  2452. Vector3.Up = function () {
  2453. return new Vector3(0.0, 1.0, 0.0);
  2454. };
  2455. /**
  2456. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2457. */
  2458. Vector3.Forward = function () {
  2459. return new Vector3(0.0, 0.0, 1.0);
  2460. };
  2461. /**
  2462. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2463. */
  2464. Vector3.Right = function () {
  2465. return new Vector3(1.0, 0.0, 0.0);
  2466. };
  2467. /**
  2468. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2469. */
  2470. Vector3.Left = function () {
  2471. return new Vector3(-1.0, 0.0, 0.0);
  2472. };
  2473. /**
  2474. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2475. * This method computes tranformed coordinates only, not transformed direction vectors.
  2476. */
  2477. Vector3.TransformCoordinates = function (vector, transformation) {
  2478. var result = Vector3.Zero();
  2479. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2480. return result;
  2481. };
  2482. /**
  2483. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2484. * This method computes tranformed coordinates only, not transformed direction vectors.
  2485. */
  2486. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2487. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2488. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2489. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2490. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2491. result.x = x / w;
  2492. result.y = y / w;
  2493. result.z = z / w;
  2494. };
  2495. /**
  2496. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2497. * This method computes tranformed coordinates only, not transformed direction vectors.
  2498. */
  2499. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2500. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2501. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2502. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2503. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2504. result.x = rx / rw;
  2505. result.y = ry / rw;
  2506. result.z = rz / rw;
  2507. };
  2508. /**
  2509. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2510. * This methods computes transformed normalized direction vectors only.
  2511. */
  2512. Vector3.TransformNormal = function (vector, transformation) {
  2513. var result = Vector3.Zero();
  2514. Vector3.TransformNormalToRef(vector, transformation, result);
  2515. return result;
  2516. };
  2517. /**
  2518. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2519. * This methods computes transformed normalized direction vectors only.
  2520. */
  2521. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2522. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2523. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2524. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2525. result.x = x;
  2526. result.y = y;
  2527. result.z = z;
  2528. };
  2529. /**
  2530. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2531. * This methods computes transformed normalized direction vectors only.
  2532. */
  2533. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2534. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2535. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2536. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2537. };
  2538. /**
  2539. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2540. */
  2541. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2551. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2552. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2553. return new Vector3(x, y, z);
  2554. };
  2555. /**
  2556. * 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".
  2557. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2558. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2559. */
  2560. Vector3.Clamp = function (value, min, max) {
  2561. var x = value.x;
  2562. x = (x > max.x) ? max.x : x;
  2563. x = (x < min.x) ? min.x : x;
  2564. var y = value.y;
  2565. y = (y > max.y) ? max.y : y;
  2566. y = (y < min.y) ? min.y : y;
  2567. var z = value.z;
  2568. z = (z > max.z) ? max.z : z;
  2569. z = (z < min.z) ? min.z : z;
  2570. return new Vector3(x, y, z);
  2571. };
  2572. /**
  2573. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2574. */
  2575. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2576. var squared = amount * amount;
  2577. var cubed = amount * squared;
  2578. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2579. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2580. var part3 = (cubed - (2.0 * squared)) + amount;
  2581. var part4 = cubed - squared;
  2582. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2583. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2584. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2585. return new Vector3(x, y, z);
  2586. };
  2587. /**
  2588. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2589. */
  2590. Vector3.Lerp = function (start, end, amount) {
  2591. var result = new Vector3(0, 0, 0);
  2592. Vector3.LerpToRef(start, end, amount, result);
  2593. return result;
  2594. };
  2595. /**
  2596. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2597. */
  2598. Vector3.LerpToRef = function (start, end, amount, result) {
  2599. result.x = start.x + ((end.x - start.x) * amount);
  2600. result.y = start.y + ((end.y - start.y) * amount);
  2601. result.z = start.z + ((end.z - start.z) * amount);
  2602. };
  2603. /**
  2604. * Returns the dot product (float) between the vectors "left" and "right".
  2605. */
  2606. Vector3.Dot = function (left, right) {
  2607. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2608. };
  2609. /**
  2610. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2611. * The cross product is then orthogonal to both "left" and "right".
  2612. */
  2613. Vector3.Cross = function (left, right) {
  2614. var result = Vector3.Zero();
  2615. Vector3.CrossToRef(left, right, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed vector "result" with the cross product of "left" and "right".
  2620. * The cross product is then orthogonal to both "left" and "right".
  2621. */
  2622. Vector3.CrossToRef = function (left, right, result) {
  2623. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2624. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2625. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2626. result.copyFrom(MathTmp.Vector3[0]);
  2627. };
  2628. /**
  2629. * Returns a new Vector3 as the normalization of the passed vector.
  2630. */
  2631. Vector3.Normalize = function (vector) {
  2632. var result = Vector3.Zero();
  2633. Vector3.NormalizeToRef(vector, result);
  2634. return result;
  2635. };
  2636. /**
  2637. * Sets the passed vector "result" with the normalization of the passed first vector.
  2638. */
  2639. Vector3.NormalizeToRef = function (vector, result) {
  2640. result.copyFrom(vector);
  2641. result.normalize();
  2642. };
  2643. Vector3.Project = function (vector, world, transform, viewport) {
  2644. var cw = viewport.width;
  2645. var ch = viewport.height;
  2646. var cx = viewport.x;
  2647. var cy = viewport.y;
  2648. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2649. 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);
  2650. var matrix = MathTmp.Matrix[0];
  2651. world.multiplyToRef(transform, matrix);
  2652. matrix.multiplyToRef(viewportMatrix, matrix);
  2653. return Vector3.TransformCoordinates(vector, matrix);
  2654. };
  2655. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2656. var matrix = MathTmp.Matrix[0];
  2657. world.multiplyToRef(transform, matrix);
  2658. matrix.invert();
  2659. source.x = source.x / viewportWidth * 2 - 1;
  2660. source.y = -(source.y / viewportHeight * 2 - 1);
  2661. var vector = Vector3.TransformCoordinates(source, matrix);
  2662. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2663. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2664. vector = vector.scale(1.0 / num);
  2665. }
  2666. return vector;
  2667. };
  2668. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2669. var result = Vector3.Zero();
  2670. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2671. return result;
  2672. };
  2673. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2674. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2675. };
  2676. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2677. var matrix = MathTmp.Matrix[0];
  2678. world.multiplyToRef(view, matrix);
  2679. matrix.multiplyToRef(projection, matrix);
  2680. matrix.invert();
  2681. var screenSource = MathTmp.Vector3[0];
  2682. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2683. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2684. screenSource.z = 2 * sourceZ - 1.0;
  2685. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2686. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2687. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2688. result.scaleInPlace(1.0 / num);
  2689. }
  2690. };
  2691. Vector3.Minimize = function (left, right) {
  2692. var min = left.clone();
  2693. min.MinimizeInPlace(right);
  2694. return min;
  2695. };
  2696. Vector3.Maximize = function (left, right) {
  2697. var max = left.clone();
  2698. max.MaximizeInPlace(right);
  2699. return max;
  2700. };
  2701. /**
  2702. * Returns the distance (float) between the vectors "value1" and "value2".
  2703. */
  2704. Vector3.Distance = function (value1, value2) {
  2705. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2706. };
  2707. /**
  2708. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2709. */
  2710. Vector3.DistanceSquared = function (value1, value2) {
  2711. var x = value1.x - value2.x;
  2712. var y = value1.y - value2.y;
  2713. var z = value1.z - value2.z;
  2714. return (x * x) + (y * y) + (z * z);
  2715. };
  2716. /**
  2717. * Returns a new Vector3 located at the center between "value1" and "value2".
  2718. */
  2719. Vector3.Center = function (value1, value2) {
  2720. var center = value1.add(value2);
  2721. center.scaleInPlace(0.5);
  2722. return center;
  2723. };
  2724. /**
  2725. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2726. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2727. * to something in order to rotate it from its local system to the given target system.
  2728. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2729. * Returns a new Vector3.
  2730. */
  2731. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2732. var rotation = Vector3.Zero();
  2733. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2734. return rotation;
  2735. };
  2736. /**
  2737. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2738. */
  2739. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2740. var quat = MathTmp.Quaternion[0];
  2741. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2742. quat.toEulerAnglesToRef(ref);
  2743. };
  2744. return Vector3;
  2745. }());
  2746. BABYLON.Vector3 = Vector3;
  2747. //Vector4 class created for EulerAngle class conversion to Quaternion
  2748. var Vector4 = /** @class */ (function () {
  2749. /**
  2750. * Creates a Vector4 object from the passed floats.
  2751. */
  2752. function Vector4(x, y, z, w) {
  2753. this.x = x;
  2754. this.y = y;
  2755. this.z = z;
  2756. this.w = w;
  2757. }
  2758. /**
  2759. * Returns the string with the Vector4 coordinates.
  2760. */
  2761. Vector4.prototype.toString = function () {
  2762. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2763. };
  2764. /**
  2765. * Returns the string "Vector4".
  2766. */
  2767. Vector4.prototype.getClassName = function () {
  2768. return "Vector4";
  2769. };
  2770. /**
  2771. * Returns the Vector4 hash code.
  2772. */
  2773. Vector4.prototype.getHashCode = function () {
  2774. var hash = this.x || 0;
  2775. hash = (hash * 397) ^ (this.y || 0);
  2776. hash = (hash * 397) ^ (this.z || 0);
  2777. hash = (hash * 397) ^ (this.w || 0);
  2778. return hash;
  2779. };
  2780. // Operators
  2781. /**
  2782. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2783. */
  2784. Vector4.prototype.asArray = function () {
  2785. var result = new Array();
  2786. this.toArray(result, 0);
  2787. return result;
  2788. };
  2789. /**
  2790. * Populates the passed array from the passed index with the Vector4 coordinates.
  2791. * Returns the Vector4.
  2792. */
  2793. Vector4.prototype.toArray = function (array, index) {
  2794. if (index === undefined) {
  2795. index = 0;
  2796. }
  2797. array[index] = this.x;
  2798. array[index + 1] = this.y;
  2799. array[index + 2] = this.z;
  2800. array[index + 3] = this.w;
  2801. return this;
  2802. };
  2803. /**
  2804. * Adds the passed vector to the current Vector4.
  2805. * Returns the updated Vector4.
  2806. */
  2807. Vector4.prototype.addInPlace = function (otherVector) {
  2808. this.x += otherVector.x;
  2809. this.y += otherVector.y;
  2810. this.z += otherVector.z;
  2811. this.w += otherVector.w;
  2812. return this;
  2813. };
  2814. /**
  2815. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2816. */
  2817. Vector4.prototype.add = function (otherVector) {
  2818. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2819. };
  2820. /**
  2821. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2822. * Returns the current Vector4.
  2823. */
  2824. Vector4.prototype.addToRef = function (otherVector, result) {
  2825. result.x = this.x + otherVector.x;
  2826. result.y = this.y + otherVector.y;
  2827. result.z = this.z + otherVector.z;
  2828. result.w = this.w + otherVector.w;
  2829. return this;
  2830. };
  2831. /**
  2832. * Subtract in place the passed vector from the current Vector4.
  2833. * Returns the updated Vector4.
  2834. */
  2835. Vector4.prototype.subtractInPlace = function (otherVector) {
  2836. this.x -= otherVector.x;
  2837. this.y -= otherVector.y;
  2838. this.z -= otherVector.z;
  2839. this.w -= otherVector.w;
  2840. return this;
  2841. };
  2842. /**
  2843. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2844. */
  2845. Vector4.prototype.subtract = function (otherVector) {
  2846. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2847. };
  2848. /**
  2849. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2850. * Returns the current Vector4.
  2851. */
  2852. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2853. result.x = this.x - otherVector.x;
  2854. result.y = this.y - otherVector.y;
  2855. result.z = this.z - otherVector.z;
  2856. result.w = this.w - otherVector.w;
  2857. return this;
  2858. };
  2859. /**
  2860. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2861. */
  2862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2864. };
  2865. /**
  2866. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2867. * Returns the current Vector4.
  2868. */
  2869. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2870. result.x = this.x - x;
  2871. result.y = this.y - y;
  2872. result.z = this.z - z;
  2873. result.w = this.w - w;
  2874. return this;
  2875. };
  2876. /**
  2877. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2878. */
  2879. Vector4.prototype.negate = function () {
  2880. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2881. };
  2882. /**
  2883. * Multiplies the current Vector4 coordinates by scale (float).
  2884. * Returns the updated Vector4.
  2885. */
  2886. Vector4.prototype.scaleInPlace = function (scale) {
  2887. this.x *= scale;
  2888. this.y *= scale;
  2889. this.z *= scale;
  2890. this.w *= scale;
  2891. return this;
  2892. };
  2893. /**
  2894. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2895. */
  2896. Vector4.prototype.scale = function (scale) {
  2897. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2898. };
  2899. /**
  2900. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2901. * Returns the current Vector4.
  2902. */
  2903. Vector4.prototype.scaleToRef = function (scale, result) {
  2904. result.x = this.x * scale;
  2905. result.y = this.y * scale;
  2906. result.z = this.z * scale;
  2907. result.w = this.w * scale;
  2908. return this;
  2909. };
  2910. /**
  2911. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2912. */
  2913. Vector4.prototype.equals = function (otherVector) {
  2914. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2915. };
  2916. /**
  2917. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2918. */
  2919. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2920. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2921. return otherVector
  2922. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2923. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2924. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2925. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2926. };
  2927. /**
  2928. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2929. */
  2930. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2931. return this.x === x && this.y === y && this.z === z && this.w === w;
  2932. };
  2933. /**
  2934. * Multiplies in place the current Vector4 by the passed one.
  2935. * Returns the updated Vector4.
  2936. */
  2937. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2938. this.x *= otherVector.x;
  2939. this.y *= otherVector.y;
  2940. this.z *= otherVector.z;
  2941. this.w *= otherVector.w;
  2942. return this;
  2943. };
  2944. /**
  2945. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2946. */
  2947. Vector4.prototype.multiply = function (otherVector) {
  2948. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2949. };
  2950. /**
  2951. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2952. * Returns the current Vector4.
  2953. */
  2954. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2955. result.x = this.x * otherVector.x;
  2956. result.y = this.y * otherVector.y;
  2957. result.z = this.z * otherVector.z;
  2958. result.w = this.w * otherVector.w;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2963. */
  2964. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2965. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2966. };
  2967. /**
  2968. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2969. */
  2970. Vector4.prototype.divide = function (otherVector) {
  2971. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2972. };
  2973. /**
  2974. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2975. * Returns the current Vector4.
  2976. */
  2977. Vector4.prototype.divideToRef = function (otherVector, result) {
  2978. result.x = this.x / otherVector.x;
  2979. result.y = this.y / otherVector.y;
  2980. result.z = this.z / otherVector.z;
  2981. result.w = this.w / otherVector.w;
  2982. return this;
  2983. };
  2984. /**
  2985. * Divides the current Vector3 coordinates by the passed ones.
  2986. * Returns the updated Vector3.
  2987. */
  2988. Vector4.prototype.divideInPlace = function (otherVector) {
  2989. return this.divideToRef(otherVector, this);
  2990. };
  2991. /**
  2992. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2993. */
  2994. Vector4.prototype.MinimizeInPlace = function (other) {
  2995. if (other.x < this.x)
  2996. this.x = other.x;
  2997. if (other.y < this.y)
  2998. this.y = other.y;
  2999. if (other.z < this.z)
  3000. this.z = other.z;
  3001. if (other.w < this.w)
  3002. this.w = other.w;
  3003. return this;
  3004. };
  3005. /**
  3006. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3007. */
  3008. Vector4.prototype.MaximizeInPlace = function (other) {
  3009. if (other.x > this.x)
  3010. this.x = other.x;
  3011. if (other.y > this.y)
  3012. this.y = other.y;
  3013. if (other.z > this.z)
  3014. this.z = other.z;
  3015. if (other.w > this.w)
  3016. this.w = other.w;
  3017. return this;
  3018. };
  3019. // Properties
  3020. /**
  3021. * Returns the Vector4 length (float).
  3022. */
  3023. Vector4.prototype.length = function () {
  3024. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3025. };
  3026. /**
  3027. * Returns the Vector4 squared length (float).
  3028. */
  3029. Vector4.prototype.lengthSquared = function () {
  3030. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3031. };
  3032. // Methods
  3033. /**
  3034. * Normalizes in place the Vector4.
  3035. * Returns the updated Vector4.
  3036. */
  3037. Vector4.prototype.normalize = function () {
  3038. var len = this.length();
  3039. if (len === 0)
  3040. return this;
  3041. var num = 1.0 / len;
  3042. this.x *= num;
  3043. this.y *= num;
  3044. this.z *= num;
  3045. this.w *= num;
  3046. return this;
  3047. };
  3048. /**
  3049. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3050. */
  3051. Vector4.prototype.toVector3 = function () {
  3052. return new Vector3(this.x, this.y, this.z);
  3053. };
  3054. /**
  3055. * Returns a new Vector4 copied from the current one.
  3056. */
  3057. Vector4.prototype.clone = function () {
  3058. return new Vector4(this.x, this.y, this.z, this.w);
  3059. };
  3060. /**
  3061. * Updates the current Vector4 with the passed one coordinates.
  3062. * Returns the updated Vector4.
  3063. */
  3064. Vector4.prototype.copyFrom = function (source) {
  3065. this.x = source.x;
  3066. this.y = source.y;
  3067. this.z = source.z;
  3068. this.w = source.w;
  3069. return this;
  3070. };
  3071. /**
  3072. * Updates the current Vector4 coordinates with the passed floats.
  3073. * Returns the updated Vector4.
  3074. */
  3075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3076. this.x = x;
  3077. this.y = y;
  3078. this.z = z;
  3079. this.w = w;
  3080. return this;
  3081. };
  3082. /**
  3083. * Updates the current Vector4 coordinates with the passed floats.
  3084. * Returns the updated Vector4.
  3085. */
  3086. Vector4.prototype.set = function (x, y, z, w) {
  3087. return this.copyFromFloats(x, y, z, w);
  3088. };
  3089. // Statics
  3090. /**
  3091. * Returns a new Vector4 set from the starting index of the passed array.
  3092. */
  3093. Vector4.FromArray = function (array, offset) {
  3094. if (!offset) {
  3095. offset = 0;
  3096. }
  3097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3098. };
  3099. /**
  3100. * Updates the passed vector "result" from the starting index of the passed array.
  3101. */
  3102. Vector4.FromArrayToRef = function (array, offset, result) {
  3103. result.x = array[offset];
  3104. result.y = array[offset + 1];
  3105. result.z = array[offset + 2];
  3106. result.w = array[offset + 3];
  3107. };
  3108. /**
  3109. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3110. */
  3111. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3112. Vector4.FromArrayToRef(array, offset, result);
  3113. };
  3114. /**
  3115. * Updates the passed vector "result" coordinates from the passed floats.
  3116. */
  3117. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3118. result.x = x;
  3119. result.y = y;
  3120. result.z = z;
  3121. result.w = w;
  3122. };
  3123. /**
  3124. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3125. */
  3126. Vector4.Zero = function () {
  3127. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3128. };
  3129. /**
  3130. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3131. */
  3132. Vector4.One = function () {
  3133. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3134. };
  3135. /**
  3136. * Returns a new normalized Vector4 from the passed one.
  3137. */
  3138. Vector4.Normalize = function (vector) {
  3139. var result = Vector4.Zero();
  3140. Vector4.NormalizeToRef(vector, result);
  3141. return result;
  3142. };
  3143. /**
  3144. * Updates the passed vector "result" from the normalization of the passed one.
  3145. */
  3146. Vector4.NormalizeToRef = function (vector, result) {
  3147. result.copyFrom(vector);
  3148. result.normalize();
  3149. };
  3150. Vector4.Minimize = function (left, right) {
  3151. var min = left.clone();
  3152. min.MinimizeInPlace(right);
  3153. return min;
  3154. };
  3155. Vector4.Maximize = function (left, right) {
  3156. var max = left.clone();
  3157. max.MaximizeInPlace(right);
  3158. return max;
  3159. };
  3160. /**
  3161. * Returns the distance (float) between the vectors "value1" and "value2".
  3162. */
  3163. Vector4.Distance = function (value1, value2) {
  3164. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3165. };
  3166. /**
  3167. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3168. */
  3169. Vector4.DistanceSquared = function (value1, value2) {
  3170. var x = value1.x - value2.x;
  3171. var y = value1.y - value2.y;
  3172. var z = value1.z - value2.z;
  3173. var w = value1.w - value2.w;
  3174. return (x * x) + (y * y) + (z * z) + (w * w);
  3175. };
  3176. /**
  3177. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3178. */
  3179. Vector4.Center = function (value1, value2) {
  3180. var center = value1.add(value2);
  3181. center.scaleInPlace(0.5);
  3182. return center;
  3183. };
  3184. /**
  3185. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3186. * This methods computes transformed normalized direction vectors only.
  3187. */
  3188. Vector4.TransformNormal = function (vector, transformation) {
  3189. var result = Vector4.Zero();
  3190. Vector4.TransformNormalToRef(vector, transformation, result);
  3191. return result;
  3192. };
  3193. /**
  3194. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3195. * This methods computes transformed normalized direction vectors only.
  3196. */
  3197. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3198. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3199. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3200. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3201. result.x = x;
  3202. result.y = y;
  3203. result.z = z;
  3204. result.w = vector.w;
  3205. };
  3206. /**
  3207. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3208. * This methods computes transformed normalized direction vectors only.
  3209. */
  3210. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3211. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3212. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3213. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3214. result.w = w;
  3215. };
  3216. return Vector4;
  3217. }());
  3218. BABYLON.Vector4 = Vector4;
  3219. var Size = /** @class */ (function () {
  3220. /**
  3221. * Creates a Size object from the passed width and height (floats).
  3222. */
  3223. function Size(width, height) {
  3224. this.width = width;
  3225. this.height = height;
  3226. }
  3227. // Returns a string with the Size width and height.
  3228. Size.prototype.toString = function () {
  3229. return "{W: " + this.width + ", H: " + this.height + "}";
  3230. };
  3231. /**
  3232. * Returns the string "Size"
  3233. */
  3234. Size.prototype.getClassName = function () {
  3235. return "Size";
  3236. };
  3237. /**
  3238. * Returns the Size hash code.
  3239. */
  3240. Size.prototype.getHashCode = function () {
  3241. var hash = this.width || 0;
  3242. hash = (hash * 397) ^ (this.height || 0);
  3243. return hash;
  3244. };
  3245. /**
  3246. * Updates the current size from the passed one.
  3247. * Returns the updated Size.
  3248. */
  3249. Size.prototype.copyFrom = function (src) {
  3250. this.width = src.width;
  3251. this.height = src.height;
  3252. };
  3253. /**
  3254. * Updates in place the current Size from the passed floats.
  3255. * Returns the updated Size.
  3256. */
  3257. Size.prototype.copyFromFloats = function (width, height) {
  3258. this.width = width;
  3259. this.height = height;
  3260. return this;
  3261. };
  3262. /**
  3263. * Updates in place the current Size from the passed floats.
  3264. * Returns the updated Size.
  3265. */
  3266. Size.prototype.set = function (width, height) {
  3267. return this.copyFromFloats(width, height);
  3268. };
  3269. /**
  3270. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3271. */
  3272. Size.prototype.multiplyByFloats = function (w, h) {
  3273. return new Size(this.width * w, this.height * h);
  3274. };
  3275. /**
  3276. * Returns a new Size copied from the passed one.
  3277. */
  3278. Size.prototype.clone = function () {
  3279. return new Size(this.width, this.height);
  3280. };
  3281. /**
  3282. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3283. */
  3284. Size.prototype.equals = function (other) {
  3285. if (!other) {
  3286. return false;
  3287. }
  3288. return (this.width === other.width) && (this.height === other.height);
  3289. };
  3290. Object.defineProperty(Size.prototype, "surface", {
  3291. /**
  3292. * Returns the surface of the Size : width * height (float).
  3293. */
  3294. get: function () {
  3295. return this.width * this.height;
  3296. },
  3297. enumerable: true,
  3298. configurable: true
  3299. });
  3300. /**
  3301. * Returns a new Size set to (0.0, 0.0)
  3302. */
  3303. Size.Zero = function () {
  3304. return new Size(0.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Size set as the addition result of the current Size and the passed one.
  3308. */
  3309. Size.prototype.add = function (otherSize) {
  3310. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3311. return r;
  3312. };
  3313. /**
  3314. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3315. */
  3316. Size.prototype.subtract = function (otherSize) {
  3317. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3318. return r;
  3319. };
  3320. /**
  3321. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3322. */
  3323. Size.Lerp = function (start, end, amount) {
  3324. var w = start.width + ((end.width - start.width) * amount);
  3325. var h = start.height + ((end.height - start.height) * amount);
  3326. return new Size(w, h);
  3327. };
  3328. return Size;
  3329. }());
  3330. BABYLON.Size = Size;
  3331. var Quaternion = /** @class */ (function () {
  3332. /**
  3333. * Creates a new Quaternion from the passed floats.
  3334. */
  3335. function Quaternion(x, y, z, w) {
  3336. if (x === void 0) { x = 0.0; }
  3337. if (y === void 0) { y = 0.0; }
  3338. if (z === void 0) { z = 0.0; }
  3339. if (w === void 0) { w = 1.0; }
  3340. this.x = x;
  3341. this.y = y;
  3342. this.z = z;
  3343. this.w = w;
  3344. }
  3345. /**
  3346. * Returns a string with the Quaternion coordinates.
  3347. */
  3348. Quaternion.prototype.toString = function () {
  3349. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3350. };
  3351. /**
  3352. * Returns the string "Quaternion".
  3353. */
  3354. Quaternion.prototype.getClassName = function () {
  3355. return "Quaternion";
  3356. };
  3357. /**
  3358. * Returns the Quaternion hash code.
  3359. */
  3360. Quaternion.prototype.getHashCode = function () {
  3361. var hash = this.x || 0;
  3362. hash = (hash * 397) ^ (this.y || 0);
  3363. hash = (hash * 397) ^ (this.z || 0);
  3364. hash = (hash * 397) ^ (this.w || 0);
  3365. return hash;
  3366. };
  3367. /**
  3368. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3369. */
  3370. Quaternion.prototype.asArray = function () {
  3371. return [this.x, this.y, this.z, this.w];
  3372. };
  3373. /**
  3374. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3375. */
  3376. Quaternion.prototype.equals = function (otherQuaternion) {
  3377. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3378. };
  3379. /**
  3380. * Returns a new Quaternion copied from the current one.
  3381. */
  3382. Quaternion.prototype.clone = function () {
  3383. return new Quaternion(this.x, this.y, this.z, this.w);
  3384. };
  3385. /**
  3386. * Updates the current Quaternion from the passed one coordinates.
  3387. * Returns the updated Quaterion.
  3388. */
  3389. Quaternion.prototype.copyFrom = function (other) {
  3390. this.x = other.x;
  3391. this.y = other.y;
  3392. this.z = other.z;
  3393. this.w = other.w;
  3394. return this;
  3395. };
  3396. /**
  3397. * Updates the current Quaternion from the passed float coordinates.
  3398. * Returns the updated Quaterion.
  3399. */
  3400. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3401. this.x = x;
  3402. this.y = y;
  3403. this.z = z;
  3404. this.w = w;
  3405. return this;
  3406. };
  3407. /**
  3408. * Updates the current Quaternion from the passed float coordinates.
  3409. * Returns the updated Quaterion.
  3410. */
  3411. Quaternion.prototype.set = function (x, y, z, w) {
  3412. return this.copyFromFloats(x, y, z, w);
  3413. };
  3414. /**
  3415. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3416. */
  3417. Quaternion.prototype.add = function (other) {
  3418. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3419. };
  3420. /**
  3421. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3422. */
  3423. Quaternion.prototype.subtract = function (other) {
  3424. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3425. };
  3426. /**
  3427. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3428. */
  3429. Quaternion.prototype.scale = function (value) {
  3430. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3431. };
  3432. /**
  3433. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3434. */
  3435. Quaternion.prototype.multiply = function (q1) {
  3436. var result = new Quaternion(0, 0, 0, 1.0);
  3437. this.multiplyToRef(q1, result);
  3438. return result;
  3439. };
  3440. /**
  3441. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3442. * Returns the current Quaternion.
  3443. */
  3444. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3445. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3446. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3447. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3448. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3449. result.copyFromFloats(x, y, z, w);
  3450. return this;
  3451. };
  3452. /**
  3453. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3454. * Returns the updated Quaternion.
  3455. */
  3456. Quaternion.prototype.multiplyInPlace = function (q1) {
  3457. this.multiplyToRef(q1, this);
  3458. return this;
  3459. };
  3460. /**
  3461. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3462. * Returns the current Quaternion.
  3463. */
  3464. Quaternion.prototype.conjugateToRef = function (ref) {
  3465. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3466. return this;
  3467. };
  3468. /**
  3469. * Conjugates in place the current Quaternion.
  3470. * Returns the updated Quaternion.
  3471. */
  3472. Quaternion.prototype.conjugateInPlace = function () {
  3473. this.x *= -1;
  3474. this.y *= -1;
  3475. this.z *= -1;
  3476. return this;
  3477. };
  3478. /**
  3479. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3480. */
  3481. Quaternion.prototype.conjugate = function () {
  3482. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3483. return result;
  3484. };
  3485. /**
  3486. * Returns the Quaternion length (float).
  3487. */
  3488. Quaternion.prototype.length = function () {
  3489. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3490. };
  3491. /**
  3492. * Normalize in place the current Quaternion.
  3493. * Returns the updated Quaternion.
  3494. */
  3495. Quaternion.prototype.normalize = function () {
  3496. var length = 1.0 / this.length();
  3497. this.x *= length;
  3498. this.y *= length;
  3499. this.z *= length;
  3500. this.w *= length;
  3501. return this;
  3502. };
  3503. /**
  3504. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3505. */
  3506. Quaternion.prototype.toEulerAngles = function (order) {
  3507. if (order === void 0) { order = "YZX"; }
  3508. var result = Vector3.Zero();
  3509. this.toEulerAnglesToRef(result, order);
  3510. return result;
  3511. };
  3512. /**
  3513. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3514. * Returns the current Quaternion.
  3515. */
  3516. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3517. if (order === void 0) { order = "YZX"; }
  3518. var qz = this.z;
  3519. var qx = this.x;
  3520. var qy = this.y;
  3521. var qw = this.w;
  3522. var sqw = qw * qw;
  3523. var sqz = qz * qz;
  3524. var sqx = qx * qx;
  3525. var sqy = qy * qy;
  3526. var zAxisY = qy * qz - qx * qw;
  3527. var limit = .4999999;
  3528. if (zAxisY < -limit) {
  3529. result.y = 2 * Math.atan2(qy, qw);
  3530. result.x = Math.PI / 2;
  3531. result.z = 0;
  3532. }
  3533. else if (zAxisY > limit) {
  3534. result.y = 2 * Math.atan2(qy, qw);
  3535. result.x = -Math.PI / 2;
  3536. result.z = 0;
  3537. }
  3538. else {
  3539. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3540. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3541. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3542. }
  3543. return this;
  3544. };
  3545. /**
  3546. * Updates the passed rotation matrix with the current Quaternion values.
  3547. * Returns the current Quaternion.
  3548. */
  3549. Quaternion.prototype.toRotationMatrix = function (result) {
  3550. var xx = this.x * this.x;
  3551. var yy = this.y * this.y;
  3552. var zz = this.z * this.z;
  3553. var xy = this.x * this.y;
  3554. var zw = this.z * this.w;
  3555. var zx = this.z * this.x;
  3556. var yw = this.y * this.w;
  3557. var yz = this.y * this.z;
  3558. var xw = this.x * this.w;
  3559. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3560. result.m[1] = 2.0 * (xy + zw);
  3561. result.m[2] = 2.0 * (zx - yw);
  3562. result.m[3] = 0;
  3563. result.m[4] = 2.0 * (xy - zw);
  3564. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3565. result.m[6] = 2.0 * (yz + xw);
  3566. result.m[7] = 0;
  3567. result.m[8] = 2.0 * (zx + yw);
  3568. result.m[9] = 2.0 * (yz - xw);
  3569. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3570. result.m[11] = 0;
  3571. result.m[12] = 0;
  3572. result.m[13] = 0;
  3573. result.m[14] = 0;
  3574. result.m[15] = 1.0;
  3575. result._markAsUpdated();
  3576. return this;
  3577. };
  3578. /**
  3579. * Updates the current Quaternion from the passed rotation matrix values.
  3580. * Returns the updated Quaternion.
  3581. */
  3582. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3583. Quaternion.FromRotationMatrixToRef(matrix, this);
  3584. return this;
  3585. };
  3586. // Statics
  3587. /**
  3588. * Returns a new Quaternion set from the passed rotation matrix values.
  3589. */
  3590. Quaternion.FromRotationMatrix = function (matrix) {
  3591. var result = new Quaternion();
  3592. Quaternion.FromRotationMatrixToRef(matrix, result);
  3593. return result;
  3594. };
  3595. /**
  3596. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3597. */
  3598. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3599. var data = matrix.m;
  3600. var m11 = data[0], m12 = data[4], m13 = data[8];
  3601. var m21 = data[1], m22 = data[5], m23 = data[9];
  3602. var m31 = data[2], m32 = data[6], m33 = data[10];
  3603. var trace = m11 + m22 + m33;
  3604. var s;
  3605. if (trace > 0) {
  3606. s = 0.5 / Math.sqrt(trace + 1.0);
  3607. result.w = 0.25 / s;
  3608. result.x = (m32 - m23) * s;
  3609. result.y = (m13 - m31) * s;
  3610. result.z = (m21 - m12) * s;
  3611. }
  3612. else if (m11 > m22 && m11 > m33) {
  3613. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3614. result.w = (m32 - m23) / s;
  3615. result.x = 0.25 * s;
  3616. result.y = (m12 + m21) / s;
  3617. result.z = (m13 + m31) / s;
  3618. }
  3619. else if (m22 > m33) {
  3620. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3621. result.w = (m13 - m31) / s;
  3622. result.x = (m12 + m21) / s;
  3623. result.y = 0.25 * s;
  3624. result.z = (m23 + m32) / s;
  3625. }
  3626. else {
  3627. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3628. result.w = (m21 - m12) / s;
  3629. result.x = (m13 + m31) / s;
  3630. result.y = (m23 + m32) / s;
  3631. result.z = 0.25 * s;
  3632. }
  3633. };
  3634. /**
  3635. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3636. */
  3637. Quaternion.Zero = function () {
  3638. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3639. };
  3640. /**
  3641. * Returns a new Quaternion as the inverted current Quaternion.
  3642. */
  3643. Quaternion.Inverse = function (q) {
  3644. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3645. };
  3646. /**
  3647. * Returns the identity Quaternion.
  3648. */
  3649. Quaternion.Identity = function () {
  3650. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3651. };
  3652. Quaternion.IsIdentity = function (quaternion) {
  3653. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3654. };
  3655. /**
  3656. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3657. */
  3658. Quaternion.RotationAxis = function (axis, angle) {
  3659. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3660. };
  3661. /**
  3662. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3663. */
  3664. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3665. var sin = Math.sin(angle / 2);
  3666. axis.normalize();
  3667. result.w = Math.cos(angle / 2);
  3668. result.x = axis.x * sin;
  3669. result.y = axis.y * sin;
  3670. result.z = axis.z * sin;
  3671. return result;
  3672. };
  3673. /**
  3674. * Retuns a new Quaternion set from the starting index of the passed array.
  3675. */
  3676. Quaternion.FromArray = function (array, offset) {
  3677. if (!offset) {
  3678. offset = 0;
  3679. }
  3680. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3681. };
  3682. /**
  3683. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3684. */
  3685. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3686. var q = new Quaternion();
  3687. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3688. return q;
  3689. };
  3690. /**
  3691. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3692. */
  3693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3695. var halfRoll = roll * 0.5;
  3696. var halfPitch = pitch * 0.5;
  3697. var halfYaw = yaw * 0.5;
  3698. var sinRoll = Math.sin(halfRoll);
  3699. var cosRoll = Math.cos(halfRoll);
  3700. var sinPitch = Math.sin(halfPitch);
  3701. var cosPitch = Math.cos(halfPitch);
  3702. var sinYaw = Math.sin(halfYaw);
  3703. var cosYaw = Math.cos(halfYaw);
  3704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3708. };
  3709. /**
  3710. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3711. */
  3712. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3713. var result = new Quaternion();
  3714. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3715. return result;
  3716. };
  3717. /**
  3718. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3719. */
  3720. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3721. // Produces a quaternion from Euler angles in the z-x-z orientation
  3722. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3723. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3724. var halfBeta = beta * 0.5;
  3725. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3726. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3727. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3728. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3729. };
  3730. /**
  3731. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3732. * cf to Vector3.RotationFromAxis() documentation.
  3733. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3734. */
  3735. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3736. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3737. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3738. return quat;
  3739. };
  3740. /**
  3741. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3742. * cf to Vector3.RotationFromAxis() documentation.
  3743. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3744. */
  3745. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3746. var rotMat = MathTmp.Matrix[0];
  3747. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3748. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3749. };
  3750. Quaternion.Slerp = function (left, right, amount) {
  3751. var result = Quaternion.Identity();
  3752. Quaternion.SlerpToRef(left, right, amount, result);
  3753. return result;
  3754. };
  3755. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3756. var num2;
  3757. var num3;
  3758. var num = amount;
  3759. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3760. var flag = false;
  3761. if (num4 < 0) {
  3762. flag = true;
  3763. num4 = -num4;
  3764. }
  3765. if (num4 > 0.999999) {
  3766. num3 = 1 - num;
  3767. num2 = flag ? -num : num;
  3768. }
  3769. else {
  3770. var num5 = Math.acos(num4);
  3771. var num6 = (1.0 / Math.sin(num5));
  3772. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3773. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3774. }
  3775. result.x = (num3 * left.x) + (num2 * right.x);
  3776. result.y = (num3 * left.y) + (num2 * right.y);
  3777. result.z = (num3 * left.z) + (num2 * right.z);
  3778. result.w = (num3 * left.w) + (num2 * right.w);
  3779. };
  3780. /**
  3781. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3782. */
  3783. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3784. var squared = amount * amount;
  3785. var cubed = amount * squared;
  3786. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3787. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3788. var part3 = (cubed - (2.0 * squared)) + amount;
  3789. var part4 = cubed - squared;
  3790. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3791. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3792. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3793. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3794. return new Quaternion(x, y, z, w);
  3795. };
  3796. return Quaternion;
  3797. }());
  3798. BABYLON.Quaternion = Quaternion;
  3799. var Matrix = /** @class */ (function () {
  3800. function Matrix() {
  3801. this._isIdentity = false;
  3802. this._isIdentityDirty = true;
  3803. this.m = new Float32Array(16);
  3804. this._markAsUpdated();
  3805. }
  3806. Matrix.prototype._markAsUpdated = function () {
  3807. this.updateFlag = Matrix._updateFlagSeed++;
  3808. this._isIdentityDirty = true;
  3809. };
  3810. // Properties
  3811. /**
  3812. * Boolean : True is the matrix is the identity matrix
  3813. */
  3814. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3815. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3816. if (this._isIdentityDirty) {
  3817. this._isIdentityDirty = false;
  3818. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3819. this._isIdentity = false;
  3820. }
  3821. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3822. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3823. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3824. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3825. this._isIdentity = false;
  3826. }
  3827. else {
  3828. this._isIdentity = true;
  3829. }
  3830. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3831. this._isIdentity = false;
  3832. }
  3833. }
  3834. return this._isIdentity;
  3835. };
  3836. /**
  3837. * Returns the matrix determinant (float).
  3838. */
  3839. Matrix.prototype.determinant = function () {
  3840. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3841. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3842. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3843. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3844. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3845. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3846. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3847. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3848. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3849. };
  3850. // Methods
  3851. /**
  3852. * Returns the matrix underlying array.
  3853. */
  3854. Matrix.prototype.toArray = function () {
  3855. return this.m;
  3856. };
  3857. /**
  3858. * Returns the matrix underlying array.
  3859. */
  3860. Matrix.prototype.asArray = function () {
  3861. return this.toArray();
  3862. };
  3863. /**
  3864. * Inverts in place the Matrix.
  3865. * Returns the Matrix inverted.
  3866. */
  3867. Matrix.prototype.invert = function () {
  3868. this.invertToRef(this);
  3869. return this;
  3870. };
  3871. /**
  3872. * Sets all the matrix elements to zero.
  3873. * Returns the Matrix.
  3874. */
  3875. Matrix.prototype.reset = function () {
  3876. for (var index = 0; index < 16; index++) {
  3877. this.m[index] = 0.0;
  3878. }
  3879. this._markAsUpdated();
  3880. return this;
  3881. };
  3882. /**
  3883. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3884. */
  3885. Matrix.prototype.add = function (other) {
  3886. var result = new Matrix();
  3887. this.addToRef(other, result);
  3888. return result;
  3889. };
  3890. /**
  3891. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3892. * Returns the Matrix.
  3893. */
  3894. Matrix.prototype.addToRef = function (other, result) {
  3895. for (var index = 0; index < 16; index++) {
  3896. result.m[index] = this.m[index] + other.m[index];
  3897. }
  3898. result._markAsUpdated();
  3899. return this;
  3900. };
  3901. /**
  3902. * Adds in place the passed matrix to the current Matrix.
  3903. * Returns the updated Matrix.
  3904. */
  3905. Matrix.prototype.addToSelf = function (other) {
  3906. for (var index = 0; index < 16; index++) {
  3907. this.m[index] += other.m[index];
  3908. }
  3909. this._markAsUpdated();
  3910. return this;
  3911. };
  3912. /**
  3913. * Sets the passed matrix with the current inverted Matrix.
  3914. * Returns the unmodified current Matrix.
  3915. */
  3916. Matrix.prototype.invertToRef = function (other) {
  3917. var l1 = this.m[0];
  3918. var l2 = this.m[1];
  3919. var l3 = this.m[2];
  3920. var l4 = this.m[3];
  3921. var l5 = this.m[4];
  3922. var l6 = this.m[5];
  3923. var l7 = this.m[6];
  3924. var l8 = this.m[7];
  3925. var l9 = this.m[8];
  3926. var l10 = this.m[9];
  3927. var l11 = this.m[10];
  3928. var l12 = this.m[11];
  3929. var l13 = this.m[12];
  3930. var l14 = this.m[13];
  3931. var l15 = this.m[14];
  3932. var l16 = this.m[15];
  3933. var l17 = (l11 * l16) - (l12 * l15);
  3934. var l18 = (l10 * l16) - (l12 * l14);
  3935. var l19 = (l10 * l15) - (l11 * l14);
  3936. var l20 = (l9 * l16) - (l12 * l13);
  3937. var l21 = (l9 * l15) - (l11 * l13);
  3938. var l22 = (l9 * l14) - (l10 * l13);
  3939. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3940. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3941. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3942. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3943. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3944. var l28 = (l7 * l16) - (l8 * l15);
  3945. var l29 = (l6 * l16) - (l8 * l14);
  3946. var l30 = (l6 * l15) - (l7 * l14);
  3947. var l31 = (l5 * l16) - (l8 * l13);
  3948. var l32 = (l5 * l15) - (l7 * l13);
  3949. var l33 = (l5 * l14) - (l6 * l13);
  3950. var l34 = (l7 * l12) - (l8 * l11);
  3951. var l35 = (l6 * l12) - (l8 * l10);
  3952. var l36 = (l6 * l11) - (l7 * l10);
  3953. var l37 = (l5 * l12) - (l8 * l9);
  3954. var l38 = (l5 * l11) - (l7 * l9);
  3955. var l39 = (l5 * l10) - (l6 * l9);
  3956. other.m[0] = l23 * l27;
  3957. other.m[4] = l24 * l27;
  3958. other.m[8] = l25 * l27;
  3959. other.m[12] = l26 * l27;
  3960. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3961. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3962. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3963. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3964. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3965. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3966. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3967. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3968. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3969. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3970. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3971. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3972. other._markAsUpdated();
  3973. return this;
  3974. };
  3975. /**
  3976. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3977. * Returns the updated Matrix.
  3978. */
  3979. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3980. this.m[12] = x;
  3981. this.m[13] = y;
  3982. this.m[14] = z;
  3983. this._markAsUpdated();
  3984. return this;
  3985. };
  3986. /**
  3987. * Inserts the translation vector in the current Matrix.
  3988. * Returns the updated Matrix.
  3989. */
  3990. Matrix.prototype.setTranslation = function (vector3) {
  3991. this.m[12] = vector3.x;
  3992. this.m[13] = vector3.y;
  3993. this.m[14] = vector3.z;
  3994. this._markAsUpdated();
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector3 as the extracted translation from the Matrix.
  3999. */
  4000. Matrix.prototype.getTranslation = function () {
  4001. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4002. };
  4003. /**
  4004. * Fill a Vector3 with the extracted translation from the Matrix.
  4005. */
  4006. Matrix.prototype.getTranslationToRef = function (result) {
  4007. result.x = this.m[12];
  4008. result.y = this.m[13];
  4009. result.z = this.m[14];
  4010. return this;
  4011. };
  4012. /**
  4013. * Remove rotation and scaling part from the Matrix.
  4014. * Returns the updated Matrix.
  4015. */
  4016. Matrix.prototype.removeRotationAndScaling = function () {
  4017. this.setRowFromFloats(0, 1, 0, 0, 0);
  4018. this.setRowFromFloats(1, 0, 1, 0, 0);
  4019. this.setRowFromFloats(2, 0, 0, 1, 0);
  4020. return this;
  4021. };
  4022. /**
  4023. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4024. */
  4025. Matrix.prototype.multiply = function (other) {
  4026. var result = new Matrix();
  4027. this.multiplyToRef(other, result);
  4028. return result;
  4029. };
  4030. /**
  4031. * Updates the current Matrix from the passed one values.
  4032. * Returns the updated Matrix.
  4033. */
  4034. Matrix.prototype.copyFrom = function (other) {
  4035. for (var index = 0; index < 16; index++) {
  4036. this.m[index] = other.m[index];
  4037. }
  4038. this._markAsUpdated();
  4039. return this;
  4040. };
  4041. /**
  4042. * Populates the passed array from the starting index with the Matrix values.
  4043. * Returns the Matrix.
  4044. */
  4045. Matrix.prototype.copyToArray = function (array, offset) {
  4046. if (offset === void 0) { offset = 0; }
  4047. for (var index = 0; index < 16; index++) {
  4048. array[offset + index] = this.m[index];
  4049. }
  4050. return this;
  4051. };
  4052. /**
  4053. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4054. */
  4055. Matrix.prototype.multiplyToRef = function (other, result) {
  4056. this.multiplyToArray(other, result.m, 0);
  4057. result._markAsUpdated();
  4058. return this;
  4059. };
  4060. /**
  4061. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4062. */
  4063. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4064. var tm0 = this.m[0];
  4065. var tm1 = this.m[1];
  4066. var tm2 = this.m[2];
  4067. var tm3 = this.m[3];
  4068. var tm4 = this.m[4];
  4069. var tm5 = this.m[5];
  4070. var tm6 = this.m[6];
  4071. var tm7 = this.m[7];
  4072. var tm8 = this.m[8];
  4073. var tm9 = this.m[9];
  4074. var tm10 = this.m[10];
  4075. var tm11 = this.m[11];
  4076. var tm12 = this.m[12];
  4077. var tm13 = this.m[13];
  4078. var tm14 = this.m[14];
  4079. var tm15 = this.m[15];
  4080. var om0 = other.m[0];
  4081. var om1 = other.m[1];
  4082. var om2 = other.m[2];
  4083. var om3 = other.m[3];
  4084. var om4 = other.m[4];
  4085. var om5 = other.m[5];
  4086. var om6 = other.m[6];
  4087. var om7 = other.m[7];
  4088. var om8 = other.m[8];
  4089. var om9 = other.m[9];
  4090. var om10 = other.m[10];
  4091. var om11 = other.m[11];
  4092. var om12 = other.m[12];
  4093. var om13 = other.m[13];
  4094. var om14 = other.m[14];
  4095. var om15 = other.m[15];
  4096. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4097. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4098. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4099. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4100. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4101. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4102. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4103. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4104. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4105. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4106. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4107. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4108. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4109. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4110. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4111. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4112. return this;
  4113. };
  4114. /**
  4115. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4116. */
  4117. Matrix.prototype.equals = function (value) {
  4118. return value &&
  4119. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4120. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4121. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4122. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4123. };
  4124. /**
  4125. * Returns a new Matrix from the current Matrix.
  4126. */
  4127. Matrix.prototype.clone = function () {
  4128. 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]);
  4129. };
  4130. /**
  4131. * Returns the string "Matrix"
  4132. */
  4133. Matrix.prototype.getClassName = function () {
  4134. return "Matrix";
  4135. };
  4136. /**
  4137. * Returns the Matrix hash code.
  4138. */
  4139. Matrix.prototype.getHashCode = function () {
  4140. var hash = this.m[0] || 0;
  4141. for (var i = 1; i < 16; i++) {
  4142. hash = (hash * 397) ^ (this.m[i] || 0);
  4143. }
  4144. return hash;
  4145. };
  4146. /**
  4147. * Decomposes the current Matrix into :
  4148. * - a scale vector3 passed as a reference to update,
  4149. * - a rotation quaternion passed as a reference to update,
  4150. * - a translation vector3 passed as a reference to update.
  4151. * Returns the boolean `true`.
  4152. */
  4153. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4154. translation.x = this.m[12];
  4155. translation.y = this.m[13];
  4156. translation.z = this.m[14];
  4157. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4158. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4159. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4160. if (this.determinant() <= 0) {
  4161. scale.y *= -1;
  4162. }
  4163. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4164. rotation.x = 0;
  4165. rotation.y = 0;
  4166. rotation.z = 0;
  4167. rotation.w = 1;
  4168. return false;
  4169. }
  4170. 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]);
  4171. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4172. return true;
  4173. };
  4174. /**
  4175. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4176. */
  4177. Matrix.prototype.getRotationMatrix = function () {
  4178. var result = Matrix.Identity();
  4179. this.getRotationMatrixToRef(result);
  4180. return result;
  4181. };
  4182. /**
  4183. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4184. * Returns the current Matrix.
  4185. */
  4186. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4187. var m = this.m;
  4188. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4189. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4190. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4191. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4192. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4193. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4194. 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);
  4195. return this;
  4196. };
  4197. // Statics
  4198. /**
  4199. * Returns a new Matrix set from the starting index of the passed array.
  4200. */
  4201. Matrix.FromArray = function (array, offset) {
  4202. var result = new Matrix();
  4203. if (!offset) {
  4204. offset = 0;
  4205. }
  4206. Matrix.FromArrayToRef(array, offset, result);
  4207. return result;
  4208. };
  4209. /**
  4210. * Sets the passed "result" matrix from the starting index of the passed array.
  4211. */
  4212. Matrix.FromArrayToRef = function (array, offset, result) {
  4213. for (var index = 0; index < 16; index++) {
  4214. result.m[index] = array[index + offset];
  4215. }
  4216. result._markAsUpdated();
  4217. };
  4218. /**
  4219. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4220. */
  4221. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4222. for (var index = 0; index < 16; index++) {
  4223. result.m[index] = array[index + offset] * scale;
  4224. }
  4225. result._markAsUpdated();
  4226. };
  4227. /**
  4228. * Sets the passed matrix "result" with the 16 passed floats.
  4229. */
  4230. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4231. result.m[0] = initialM11;
  4232. result.m[1] = initialM12;
  4233. result.m[2] = initialM13;
  4234. result.m[3] = initialM14;
  4235. result.m[4] = initialM21;
  4236. result.m[5] = initialM22;
  4237. result.m[6] = initialM23;
  4238. result.m[7] = initialM24;
  4239. result.m[8] = initialM31;
  4240. result.m[9] = initialM32;
  4241. result.m[10] = initialM33;
  4242. result.m[11] = initialM34;
  4243. result.m[12] = initialM41;
  4244. result.m[13] = initialM42;
  4245. result.m[14] = initialM43;
  4246. result.m[15] = initialM44;
  4247. result._markAsUpdated();
  4248. };
  4249. /**
  4250. * Returns the index-th row of the current matrix as a new Vector4.
  4251. */
  4252. Matrix.prototype.getRow = function (index) {
  4253. if (index < 0 || index > 3) {
  4254. return null;
  4255. }
  4256. var i = index * 4;
  4257. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4258. };
  4259. /**
  4260. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4261. * Returns the updated Matrix.
  4262. */
  4263. Matrix.prototype.setRow = function (index, row) {
  4264. if (index < 0 || index > 3) {
  4265. return this;
  4266. }
  4267. var i = index * 4;
  4268. this.m[i + 0] = row.x;
  4269. this.m[i + 1] = row.y;
  4270. this.m[i + 2] = row.z;
  4271. this.m[i + 3] = row.w;
  4272. this._markAsUpdated();
  4273. return this;
  4274. };
  4275. /**
  4276. * Compute the transpose of the matrix.
  4277. * Returns a new Matrix.
  4278. */
  4279. Matrix.prototype.transpose = function () {
  4280. return Matrix.Transpose(this);
  4281. };
  4282. /**
  4283. * Compute the transpose of the matrix.
  4284. * Returns the current matrix.
  4285. */
  4286. Matrix.prototype.transposeToRef = function (result) {
  4287. Matrix.TransposeToRef(this, result);
  4288. return this;
  4289. };
  4290. /**
  4291. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4292. * Returns the updated Matrix.
  4293. */
  4294. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4295. if (index < 0 || index > 3) {
  4296. return this;
  4297. }
  4298. var i = index * 4;
  4299. this.m[i + 0] = x;
  4300. this.m[i + 1] = y;
  4301. this.m[i + 2] = z;
  4302. this.m[i + 3] = w;
  4303. this._markAsUpdated();
  4304. return this;
  4305. };
  4306. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4307. /**
  4308. * Static identity matrix to be used as readonly matrix
  4309. * Must not be updated.
  4310. */
  4311. get: function () {
  4312. return Matrix._identityReadOnly;
  4313. },
  4314. enumerable: true,
  4315. configurable: true
  4316. });
  4317. /**
  4318. * Returns a new Matrix set from the 16 passed floats.
  4319. */
  4320. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4321. var result = new Matrix();
  4322. result.m[0] = initialM11;
  4323. result.m[1] = initialM12;
  4324. result.m[2] = initialM13;
  4325. result.m[3] = initialM14;
  4326. result.m[4] = initialM21;
  4327. result.m[5] = initialM22;
  4328. result.m[6] = initialM23;
  4329. result.m[7] = initialM24;
  4330. result.m[8] = initialM31;
  4331. result.m[9] = initialM32;
  4332. result.m[10] = initialM33;
  4333. result.m[11] = initialM34;
  4334. result.m[12] = initialM41;
  4335. result.m[13] = initialM42;
  4336. result.m[14] = initialM43;
  4337. result.m[15] = initialM44;
  4338. return result;
  4339. };
  4340. /**
  4341. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4342. */
  4343. Matrix.Compose = function (scale, rotation, translation) {
  4344. var result = Matrix.Identity();
  4345. Matrix.ComposeToRef(scale, rotation, translation, result);
  4346. return result;
  4347. };
  4348. /**
  4349. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4350. */
  4351. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4352. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4353. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4354. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4355. result.setTranslation(translation);
  4356. };
  4357. /**
  4358. * Returns a new indentity Matrix.
  4359. */
  4360. Matrix.Identity = function () {
  4361. 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);
  4362. };
  4363. /**
  4364. * Sets the passed "result" as an identity matrix.
  4365. */
  4366. Matrix.IdentityToRef = function (result) {
  4367. 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);
  4368. };
  4369. /**
  4370. * Returns a new zero Matrix.
  4371. */
  4372. Matrix.Zero = function () {
  4373. 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);
  4374. };
  4375. /**
  4376. * Returns a new rotation matrix for "angle" radians around the X axis.
  4377. */
  4378. Matrix.RotationX = function (angle) {
  4379. var result = new Matrix();
  4380. Matrix.RotationXToRef(angle, result);
  4381. return result;
  4382. };
  4383. /**
  4384. * Returns a new Matrix as the passed inverted one.
  4385. */
  4386. Matrix.Invert = function (source) {
  4387. var result = new Matrix();
  4388. source.invertToRef(result);
  4389. return result;
  4390. };
  4391. /**
  4392. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4393. */
  4394. Matrix.RotationXToRef = function (angle, result) {
  4395. var s = Math.sin(angle);
  4396. var c = Math.cos(angle);
  4397. result.m[0] = 1.0;
  4398. result.m[15] = 1.0;
  4399. result.m[5] = c;
  4400. result.m[10] = c;
  4401. result.m[9] = -s;
  4402. result.m[6] = s;
  4403. result.m[1] = 0.0;
  4404. result.m[2] = 0.0;
  4405. result.m[3] = 0.0;
  4406. result.m[4] = 0.0;
  4407. result.m[7] = 0.0;
  4408. result.m[8] = 0.0;
  4409. result.m[11] = 0.0;
  4410. result.m[12] = 0.0;
  4411. result.m[13] = 0.0;
  4412. result.m[14] = 0.0;
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4417. */
  4418. Matrix.RotationY = function (angle) {
  4419. var result = new Matrix();
  4420. Matrix.RotationYToRef(angle, result);
  4421. return result;
  4422. };
  4423. /**
  4424. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4425. */
  4426. Matrix.RotationYToRef = function (angle, result) {
  4427. var s = Math.sin(angle);
  4428. var c = Math.cos(angle);
  4429. result.m[5] = 1.0;
  4430. result.m[15] = 1.0;
  4431. result.m[0] = c;
  4432. result.m[2] = -s;
  4433. result.m[8] = s;
  4434. result.m[10] = c;
  4435. result.m[1] = 0.0;
  4436. result.m[3] = 0.0;
  4437. result.m[4] = 0.0;
  4438. result.m[6] = 0.0;
  4439. result.m[7] = 0.0;
  4440. result.m[9] = 0.0;
  4441. result.m[11] = 0.0;
  4442. result.m[12] = 0.0;
  4443. result.m[13] = 0.0;
  4444. result.m[14] = 0.0;
  4445. result._markAsUpdated();
  4446. };
  4447. /**
  4448. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4449. */
  4450. Matrix.RotationZ = function (angle) {
  4451. var result = new Matrix();
  4452. Matrix.RotationZToRef(angle, result);
  4453. return result;
  4454. };
  4455. /**
  4456. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4457. */
  4458. Matrix.RotationZToRef = function (angle, result) {
  4459. var s = Math.sin(angle);
  4460. var c = Math.cos(angle);
  4461. result.m[10] = 1.0;
  4462. result.m[15] = 1.0;
  4463. result.m[0] = c;
  4464. result.m[1] = s;
  4465. result.m[4] = -s;
  4466. result.m[5] = c;
  4467. result.m[2] = 0.0;
  4468. result.m[3] = 0.0;
  4469. result.m[6] = 0.0;
  4470. result.m[7] = 0.0;
  4471. result.m[8] = 0.0;
  4472. result.m[9] = 0.0;
  4473. result.m[11] = 0.0;
  4474. result.m[12] = 0.0;
  4475. result.m[13] = 0.0;
  4476. result.m[14] = 0.0;
  4477. result._markAsUpdated();
  4478. };
  4479. /**
  4480. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4481. */
  4482. Matrix.RotationAxis = function (axis, angle) {
  4483. var result = Matrix.Zero();
  4484. Matrix.RotationAxisToRef(axis, angle, result);
  4485. return result;
  4486. };
  4487. /**
  4488. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4489. */
  4490. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4491. var s = Math.sin(-angle);
  4492. var c = Math.cos(-angle);
  4493. var c1 = 1 - c;
  4494. axis.normalize();
  4495. result.m[0] = (axis.x * axis.x) * c1 + c;
  4496. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4497. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4498. result.m[3] = 0.0;
  4499. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4500. result.m[5] = (axis.y * axis.y) * c1 + c;
  4501. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4502. result.m[7] = 0.0;
  4503. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4504. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4505. result.m[10] = (axis.z * axis.z) * c1 + c;
  4506. result.m[11] = 0.0;
  4507. result.m[15] = 1.0;
  4508. result._markAsUpdated();
  4509. };
  4510. /**
  4511. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4512. */
  4513. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4514. var result = new Matrix();
  4515. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4516. return result;
  4517. };
  4518. /**
  4519. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4520. */
  4521. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4522. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4523. this._tempQuaternion.toRotationMatrix(result);
  4524. };
  4525. /**
  4526. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4527. */
  4528. Matrix.Scaling = function (x, y, z) {
  4529. var result = Matrix.Zero();
  4530. Matrix.ScalingToRef(x, y, z, result);
  4531. return result;
  4532. };
  4533. /**
  4534. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4535. */
  4536. Matrix.ScalingToRef = function (x, y, z, result) {
  4537. result.m[0] = x;
  4538. result.m[1] = 0.0;
  4539. result.m[2] = 0.0;
  4540. result.m[3] = 0.0;
  4541. result.m[4] = 0.0;
  4542. result.m[5] = y;
  4543. result.m[6] = 0.0;
  4544. result.m[7] = 0.0;
  4545. result.m[8] = 0.0;
  4546. result.m[9] = 0.0;
  4547. result.m[10] = z;
  4548. result.m[11] = 0.0;
  4549. result.m[12] = 0.0;
  4550. result.m[13] = 0.0;
  4551. result.m[14] = 0.0;
  4552. result.m[15] = 1.0;
  4553. result._markAsUpdated();
  4554. };
  4555. /**
  4556. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4557. */
  4558. Matrix.Translation = function (x, y, z) {
  4559. var result = Matrix.Identity();
  4560. Matrix.TranslationToRef(x, y, z, result);
  4561. return result;
  4562. };
  4563. /**
  4564. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4565. */
  4566. Matrix.TranslationToRef = function (x, y, z, result) {
  4567. 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);
  4568. };
  4569. /**
  4570. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4571. */
  4572. Matrix.Lerp = function (startValue, endValue, gradient) {
  4573. var result = Matrix.Zero();
  4574. for (var index = 0; index < 16; index++) {
  4575. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4576. }
  4577. result._markAsUpdated();
  4578. return result;
  4579. };
  4580. /**
  4581. * Returns a new Matrix whose values are computed by :
  4582. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4583. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4584. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4585. */
  4586. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4587. var startScale = new Vector3(0, 0, 0);
  4588. var startRotation = new Quaternion();
  4589. var startTranslation = new Vector3(0, 0, 0);
  4590. startValue.decompose(startScale, startRotation, startTranslation);
  4591. var endScale = new Vector3(0, 0, 0);
  4592. var endRotation = new Quaternion();
  4593. var endTranslation = new Vector3(0, 0, 0);
  4594. endValue.decompose(endScale, endRotation, endTranslation);
  4595. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4596. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4597. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4598. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4599. };
  4600. /**
  4601. * 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".
  4602. * This methods works for a Left-Handed system.
  4603. */
  4604. Matrix.LookAtLH = function (eye, target, up) {
  4605. var result = Matrix.Zero();
  4606. Matrix.LookAtLHToRef(eye, target, up, result);
  4607. return result;
  4608. };
  4609. /**
  4610. * 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".
  4611. * This methods works for a Left-Handed system.
  4612. */
  4613. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4614. // Z axis
  4615. target.subtractToRef(eye, this._zAxis);
  4616. this._zAxis.normalize();
  4617. // X axis
  4618. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4619. if (this._xAxis.lengthSquared() === 0) {
  4620. this._xAxis.x = 1.0;
  4621. }
  4622. else {
  4623. this._xAxis.normalize();
  4624. }
  4625. // Y axis
  4626. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4627. this._yAxis.normalize();
  4628. // Eye angles
  4629. var ex = -Vector3.Dot(this._xAxis, eye);
  4630. var ey = -Vector3.Dot(this._yAxis, eye);
  4631. var ez = -Vector3.Dot(this._zAxis, eye);
  4632. 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);
  4633. };
  4634. /**
  4635. * 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".
  4636. * This methods works for a Right-Handed system.
  4637. */
  4638. Matrix.LookAtRH = function (eye, target, up) {
  4639. var result = Matrix.Zero();
  4640. Matrix.LookAtRHToRef(eye, target, up, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * 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".
  4645. * This methods works for a Left-Handed system.
  4646. */
  4647. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4648. // Z axis
  4649. eye.subtractToRef(target, this._zAxis);
  4650. this._zAxis.normalize();
  4651. // X axis
  4652. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4653. if (this._xAxis.lengthSquared() === 0) {
  4654. this._xAxis.x = 1.0;
  4655. }
  4656. else {
  4657. this._xAxis.normalize();
  4658. }
  4659. // Y axis
  4660. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4661. this._yAxis.normalize();
  4662. // Eye angles
  4663. var ex = -Vector3.Dot(this._xAxis, eye);
  4664. var ey = -Vector3.Dot(this._yAxis, eye);
  4665. var ez = -Vector3.Dot(this._zAxis, eye);
  4666. 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);
  4667. };
  4668. /**
  4669. * 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.
  4670. */
  4671. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4672. var matrix = Matrix.Zero();
  4673. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4674. return matrix;
  4675. };
  4676. /**
  4677. * 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.
  4678. */
  4679. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4680. var n = znear;
  4681. var f = zfar;
  4682. var a = 2.0 / width;
  4683. var b = 2.0 / height;
  4684. var c = 2.0 / (f - n);
  4685. var d = -(f + n) / (f - n);
  4686. 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);
  4687. };
  4688. /**
  4689. * 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.
  4690. */
  4691. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4692. var matrix = Matrix.Zero();
  4693. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4694. return matrix;
  4695. };
  4696. /**
  4697. * 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.
  4698. */
  4699. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4700. var n = znear;
  4701. var f = zfar;
  4702. var a = 2.0 / (right - left);
  4703. var b = 2.0 / (top - bottom);
  4704. var c = 2.0 / (f - n);
  4705. var d = -(f + n) / (f - n);
  4706. var i0 = (left + right) / (left - right);
  4707. var i1 = (top + bottom) / (bottom - top);
  4708. 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);
  4709. };
  4710. /**
  4711. * 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.
  4712. */
  4713. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4714. var matrix = Matrix.Zero();
  4715. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4716. return matrix;
  4717. };
  4718. /**
  4719. * 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.
  4720. */
  4721. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4722. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4723. result.m[10] *= -1.0;
  4724. };
  4725. /**
  4726. * 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.
  4727. */
  4728. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4729. var matrix = Matrix.Zero();
  4730. var n = znear;
  4731. var f = zfar;
  4732. var a = 2.0 * n / width;
  4733. var b = 2.0 * n / height;
  4734. var c = (f + n) / (f - n);
  4735. var d = -2.0 * f * n / (f - n);
  4736. 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);
  4737. return matrix;
  4738. };
  4739. /**
  4740. * 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.
  4741. */
  4742. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4743. var matrix = Matrix.Zero();
  4744. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4745. return matrix;
  4746. };
  4747. /**
  4748. * 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.
  4749. */
  4750. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4751. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4752. var n = znear;
  4753. var f = zfar;
  4754. var t = 1.0 / (Math.tan(fov * 0.5));
  4755. var a = isVerticalFovFixed ? (t / aspect) : t;
  4756. var b = isVerticalFovFixed ? t : (t * aspect);
  4757. var c = (f + n) / (f - n);
  4758. var d = -2.0 * f * n / (f - n);
  4759. 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);
  4760. };
  4761. /**
  4762. * 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.
  4763. */
  4764. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4765. var matrix = Matrix.Zero();
  4766. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4767. return matrix;
  4768. };
  4769. /**
  4770. * 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.
  4771. */
  4772. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4773. //alternatively this could be expressed as:
  4774. // m = PerspectiveFovLHToRef
  4775. // m[10] *= -1.0;
  4776. // m[11] *= -1.0;
  4777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4778. var n = znear;
  4779. var f = zfar;
  4780. var t = 1.0 / (Math.tan(fov * 0.5));
  4781. var a = isVerticalFovFixed ? (t / aspect) : t;
  4782. var b = isVerticalFovFixed ? t : (t * aspect);
  4783. var c = -(f + n) / (f - n);
  4784. var d = -2 * f * n / (f - n);
  4785. 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);
  4786. };
  4787. /**
  4788. * 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.
  4789. */
  4790. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4791. if (rightHanded === void 0) { rightHanded = false; }
  4792. var rightHandedFactor = rightHanded ? -1 : 1;
  4793. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4794. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4795. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4796. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4797. var xScale = 2.0 / (leftTan + rightTan);
  4798. var yScale = 2.0 / (upTan + downTan);
  4799. result.m[0] = xScale;
  4800. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4801. result.m[5] = yScale;
  4802. result.m[6] = result.m[7] = 0.0;
  4803. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4804. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4805. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4806. result.m[10] = -zfar / (znear - zfar);
  4807. result.m[11] = 1.0 * rightHandedFactor;
  4808. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4809. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4810. // result.m[14] = (znear * zfar) / (znear - zfar);
  4811. result._markAsUpdated();
  4812. };
  4813. /**
  4814. * Returns the final transformation matrix : world * view * projection * viewport
  4815. */
  4816. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4817. var cw = viewport.width;
  4818. var ch = viewport.height;
  4819. var cx = viewport.x;
  4820. var cy = viewport.y;
  4821. 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);
  4822. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4823. };
  4824. /**
  4825. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4826. */
  4827. Matrix.GetAsMatrix2x2 = function (matrix) {
  4828. return new Float32Array([
  4829. matrix.m[0], matrix.m[1],
  4830. matrix.m[4], matrix.m[5]
  4831. ]);
  4832. };
  4833. /**
  4834. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4835. */
  4836. Matrix.GetAsMatrix3x3 = function (matrix) {
  4837. return new Float32Array([
  4838. matrix.m[0], matrix.m[1], matrix.m[2],
  4839. matrix.m[4], matrix.m[5], matrix.m[6],
  4840. matrix.m[8], matrix.m[9], matrix.m[10]
  4841. ]);
  4842. };
  4843. /**
  4844. * Compute the transpose of the passed Matrix.
  4845. * Returns a new Matrix.
  4846. */
  4847. Matrix.Transpose = function (matrix) {
  4848. var result = new Matrix();
  4849. Matrix.TransposeToRef(matrix, result);
  4850. return result;
  4851. };
  4852. /**
  4853. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4854. */
  4855. Matrix.TransposeToRef = function (matrix, result) {
  4856. result.m[0] = matrix.m[0];
  4857. result.m[1] = matrix.m[4];
  4858. result.m[2] = matrix.m[8];
  4859. result.m[3] = matrix.m[12];
  4860. result.m[4] = matrix.m[1];
  4861. result.m[5] = matrix.m[5];
  4862. result.m[6] = matrix.m[9];
  4863. result.m[7] = matrix.m[13];
  4864. result.m[8] = matrix.m[2];
  4865. result.m[9] = matrix.m[6];
  4866. result.m[10] = matrix.m[10];
  4867. result.m[11] = matrix.m[14];
  4868. result.m[12] = matrix.m[3];
  4869. result.m[13] = matrix.m[7];
  4870. result.m[14] = matrix.m[11];
  4871. result.m[15] = matrix.m[15];
  4872. };
  4873. /**
  4874. * Returns a new Matrix as the reflection matrix across the passed plane.
  4875. */
  4876. Matrix.Reflection = function (plane) {
  4877. var matrix = new Matrix();
  4878. Matrix.ReflectionToRef(plane, matrix);
  4879. return matrix;
  4880. };
  4881. /**
  4882. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4883. */
  4884. Matrix.ReflectionToRef = function (plane, result) {
  4885. plane.normalize();
  4886. var x = plane.normal.x;
  4887. var y = plane.normal.y;
  4888. var z = plane.normal.z;
  4889. var temp = -2 * x;
  4890. var temp2 = -2 * y;
  4891. var temp3 = -2 * z;
  4892. result.m[0] = (temp * x) + 1;
  4893. result.m[1] = temp2 * x;
  4894. result.m[2] = temp3 * x;
  4895. result.m[3] = 0.0;
  4896. result.m[4] = temp * y;
  4897. result.m[5] = (temp2 * y) + 1;
  4898. result.m[6] = temp3 * y;
  4899. result.m[7] = 0.0;
  4900. result.m[8] = temp * z;
  4901. result.m[9] = temp2 * z;
  4902. result.m[10] = (temp3 * z) + 1;
  4903. result.m[11] = 0.0;
  4904. result.m[12] = temp * plane.d;
  4905. result.m[13] = temp2 * plane.d;
  4906. result.m[14] = temp3 * plane.d;
  4907. result.m[15] = 1.0;
  4908. result._markAsUpdated();
  4909. };
  4910. /**
  4911. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4912. */
  4913. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4914. result.m[0] = xaxis.x;
  4915. result.m[1] = xaxis.y;
  4916. result.m[2] = xaxis.z;
  4917. result.m[3] = 0.0;
  4918. result.m[4] = yaxis.x;
  4919. result.m[5] = yaxis.y;
  4920. result.m[6] = yaxis.z;
  4921. result.m[7] = 0.0;
  4922. result.m[8] = zaxis.x;
  4923. result.m[9] = zaxis.y;
  4924. result.m[10] = zaxis.z;
  4925. result.m[11] = 0.0;
  4926. result.m[12] = 0.0;
  4927. result.m[13] = 0.0;
  4928. result.m[14] = 0.0;
  4929. result.m[15] = 1.0;
  4930. result._markAsUpdated();
  4931. };
  4932. /**
  4933. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4934. */
  4935. Matrix.FromQuaternionToRef = function (quat, result) {
  4936. var xx = quat.x * quat.x;
  4937. var yy = quat.y * quat.y;
  4938. var zz = quat.z * quat.z;
  4939. var xy = quat.x * quat.y;
  4940. var zw = quat.z * quat.w;
  4941. var zx = quat.z * quat.x;
  4942. var yw = quat.y * quat.w;
  4943. var yz = quat.y * quat.z;
  4944. var xw = quat.x * quat.w;
  4945. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4946. result.m[1] = 2.0 * (xy + zw);
  4947. result.m[2] = 2.0 * (zx - yw);
  4948. result.m[3] = 0.0;
  4949. result.m[4] = 2.0 * (xy - zw);
  4950. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4951. result.m[6] = 2.0 * (yz + xw);
  4952. result.m[7] = 0.0;
  4953. result.m[8] = 2.0 * (zx + yw);
  4954. result.m[9] = 2.0 * (yz - xw);
  4955. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4956. result.m[11] = 0.0;
  4957. result.m[12] = 0.0;
  4958. result.m[13] = 0.0;
  4959. result.m[14] = 0.0;
  4960. result.m[15] = 1.0;
  4961. result._markAsUpdated();
  4962. };
  4963. Matrix._tempQuaternion = new Quaternion();
  4964. Matrix._xAxis = Vector3.Zero();
  4965. Matrix._yAxis = Vector3.Zero();
  4966. Matrix._zAxis = Vector3.Zero();
  4967. Matrix._updateFlagSeed = 0;
  4968. Matrix._identityReadOnly = Matrix.Identity();
  4969. return Matrix;
  4970. }());
  4971. BABYLON.Matrix = Matrix;
  4972. var Plane = /** @class */ (function () {
  4973. /**
  4974. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4975. */
  4976. function Plane(a, b, c, d) {
  4977. this.normal = new Vector3(a, b, c);
  4978. this.d = d;
  4979. }
  4980. /**
  4981. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4982. */
  4983. Plane.prototype.asArray = function () {
  4984. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4985. };
  4986. // Methods
  4987. /**
  4988. * Returns a new plane copied from the current Plane.
  4989. */
  4990. Plane.prototype.clone = function () {
  4991. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4992. };
  4993. /**
  4994. * Returns the string "Plane".
  4995. */
  4996. Plane.prototype.getClassName = function () {
  4997. return "Plane";
  4998. };
  4999. /**
  5000. * Returns the Plane hash code.
  5001. */
  5002. Plane.prototype.getHashCode = function () {
  5003. var hash = this.normal.getHashCode();
  5004. hash = (hash * 397) ^ (this.d || 0);
  5005. return hash;
  5006. };
  5007. /**
  5008. * Normalize the current Plane in place.
  5009. * Returns the updated Plane.
  5010. */
  5011. Plane.prototype.normalize = function () {
  5012. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5013. var magnitude = 0.0;
  5014. if (norm !== 0) {
  5015. magnitude = 1.0 / norm;
  5016. }
  5017. this.normal.x *= magnitude;
  5018. this.normal.y *= magnitude;
  5019. this.normal.z *= magnitude;
  5020. this.d *= magnitude;
  5021. return this;
  5022. };
  5023. /**
  5024. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5025. */
  5026. Plane.prototype.transform = function (transformation) {
  5027. var transposedMatrix = Matrix.Transpose(transformation);
  5028. var x = this.normal.x;
  5029. var y = this.normal.y;
  5030. var z = this.normal.z;
  5031. var d = this.d;
  5032. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5033. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5034. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5035. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5036. return new Plane(normalX, normalY, normalZ, finalD);
  5037. };
  5038. /**
  5039. * Returns the dot product (float) of the point coordinates and the plane normal.
  5040. */
  5041. Plane.prototype.dotCoordinate = function (point) {
  5042. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5043. };
  5044. /**
  5045. * Updates the current Plane from the plane defined by the three passed points.
  5046. * Returns the updated Plane.
  5047. */
  5048. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5049. var x1 = point2.x - point1.x;
  5050. var y1 = point2.y - point1.y;
  5051. var z1 = point2.z - point1.z;
  5052. var x2 = point3.x - point1.x;
  5053. var y2 = point3.y - point1.y;
  5054. var z2 = point3.z - point1.z;
  5055. var yz = (y1 * z2) - (z1 * y2);
  5056. var xz = (z1 * x2) - (x1 * z2);
  5057. var xy = (x1 * y2) - (y1 * x2);
  5058. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5059. var invPyth;
  5060. if (pyth !== 0) {
  5061. invPyth = 1.0 / pyth;
  5062. }
  5063. else {
  5064. invPyth = 0.0;
  5065. }
  5066. this.normal.x = yz * invPyth;
  5067. this.normal.y = xz * invPyth;
  5068. this.normal.z = xy * invPyth;
  5069. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5070. return this;
  5071. };
  5072. /**
  5073. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5074. */
  5075. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5076. var dot = Vector3.Dot(this.normal, direction);
  5077. return (dot <= epsilon);
  5078. };
  5079. /**
  5080. * Returns the signed distance (float) from the passed point to the Plane.
  5081. */
  5082. Plane.prototype.signedDistanceTo = function (point) {
  5083. return Vector3.Dot(point, this.normal) + this.d;
  5084. };
  5085. // Statics
  5086. /**
  5087. * Returns a new Plane from the passed array.
  5088. */
  5089. Plane.FromArray = function (array) {
  5090. return new Plane(array[0], array[1], array[2], array[3]);
  5091. };
  5092. /**
  5093. * Returns a new Plane defined by the three passed points.
  5094. */
  5095. Plane.FromPoints = function (point1, point2, point3) {
  5096. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5097. result.copyFromPoints(point1, point2, point3);
  5098. return result;
  5099. };
  5100. /**
  5101. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5102. * Note : the vector "normal" is updated because normalized.
  5103. */
  5104. Plane.FromPositionAndNormal = function (origin, normal) {
  5105. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5106. normal.normalize();
  5107. result.normal = normal;
  5108. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5109. return result;
  5110. };
  5111. /**
  5112. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5113. */
  5114. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5115. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5116. return Vector3.Dot(point, normal) + d;
  5117. };
  5118. return Plane;
  5119. }());
  5120. BABYLON.Plane = Plane;
  5121. var Viewport = /** @class */ (function () {
  5122. /**
  5123. * Creates a Viewport object located at (x, y) and sized (width, height).
  5124. */
  5125. function Viewport(x, y, width, height) {
  5126. this.x = x;
  5127. this.y = y;
  5128. this.width = width;
  5129. this.height = height;
  5130. }
  5131. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5132. if (renderWidthOrEngine.getRenderWidth) {
  5133. var engine = renderWidthOrEngine;
  5134. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5135. }
  5136. var renderWidth = renderWidthOrEngine;
  5137. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5138. };
  5139. /**
  5140. * Returns a new Viewport copied from the current one.
  5141. */
  5142. Viewport.prototype.clone = function () {
  5143. return new Viewport(this.x, this.y, this.width, this.height);
  5144. };
  5145. return Viewport;
  5146. }());
  5147. BABYLON.Viewport = Viewport;
  5148. var Frustum = /** @class */ (function () {
  5149. function Frustum() {
  5150. }
  5151. /**
  5152. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5153. */
  5154. Frustum.GetPlanes = function (transform) {
  5155. var frustumPlanes = [];
  5156. for (var index = 0; index < 6; index++) {
  5157. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5158. }
  5159. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5160. return frustumPlanes;
  5161. };
  5162. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5163. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5164. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5165. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5166. frustumPlane.d = transform.m[15] + transform.m[14];
  5167. frustumPlane.normalize();
  5168. };
  5169. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5170. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5171. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5172. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5173. frustumPlane.d = transform.m[15] - transform.m[14];
  5174. frustumPlane.normalize();
  5175. };
  5176. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5177. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5178. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5179. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5180. frustumPlane.d = transform.m[15] + transform.m[12];
  5181. frustumPlane.normalize();
  5182. };
  5183. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5184. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5185. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5186. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5187. frustumPlane.d = transform.m[15] - transform.m[12];
  5188. frustumPlane.normalize();
  5189. };
  5190. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5191. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5192. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5193. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5194. frustumPlane.d = transform.m[15] - transform.m[13];
  5195. frustumPlane.normalize();
  5196. };
  5197. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5198. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5199. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5200. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5201. frustumPlane.d = transform.m[15] + transform.m[13];
  5202. frustumPlane.normalize();
  5203. };
  5204. /**
  5205. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5206. */
  5207. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5208. // Near
  5209. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5210. // Far
  5211. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5212. // Left
  5213. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5214. // Right
  5215. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5216. // Top
  5217. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5218. // Bottom
  5219. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5220. };
  5221. return Frustum;
  5222. }());
  5223. BABYLON.Frustum = Frustum;
  5224. var Space;
  5225. (function (Space) {
  5226. Space[Space["LOCAL"] = 0] = "LOCAL";
  5227. Space[Space["WORLD"] = 1] = "WORLD";
  5228. Space[Space["BONE"] = 2] = "BONE";
  5229. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5230. var Axis = /** @class */ (function () {
  5231. function Axis() {
  5232. }
  5233. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5234. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5235. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5236. return Axis;
  5237. }());
  5238. BABYLON.Axis = Axis;
  5239. ;
  5240. var BezierCurve = /** @class */ (function () {
  5241. function BezierCurve() {
  5242. }
  5243. /**
  5244. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5245. */
  5246. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5247. // Extract X (which is equal to time here)
  5248. var f0 = 1 - 3 * x2 + 3 * x1;
  5249. var f1 = 3 * x2 - 6 * x1;
  5250. var f2 = 3 * x1;
  5251. var refinedT = t;
  5252. for (var i = 0; i < 5; i++) {
  5253. var refinedT2 = refinedT * refinedT;
  5254. var refinedT3 = refinedT2 * refinedT;
  5255. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5256. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5257. refinedT -= (x - t) * slope;
  5258. refinedT = Math.min(1, Math.max(0, refinedT));
  5259. }
  5260. // Resolve cubic bezier for the given x
  5261. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5262. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5263. Math.pow(refinedT, 3);
  5264. };
  5265. return BezierCurve;
  5266. }());
  5267. BABYLON.BezierCurve = BezierCurve;
  5268. var Orientation;
  5269. (function (Orientation) {
  5270. Orientation[Orientation["CW"] = 0] = "CW";
  5271. Orientation[Orientation["CCW"] = 1] = "CCW";
  5272. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5273. var Angle = /** @class */ (function () {
  5274. /**
  5275. * Creates an Angle object of "radians" radians (float).
  5276. */
  5277. function Angle(radians) {
  5278. var _this = this;
  5279. /**
  5280. * Returns the Angle value in degrees (float).
  5281. */
  5282. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5283. /**
  5284. * Returns the Angle value in radians (float).
  5285. */
  5286. this.radians = function () { return _this._radians; };
  5287. this._radians = radians;
  5288. if (this._radians < 0.0)
  5289. this._radians += (2.0 * Math.PI);
  5290. }
  5291. /**
  5292. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5293. */
  5294. Angle.BetweenTwoPoints = function (a, b) {
  5295. var delta = b.subtract(a);
  5296. var theta = Math.atan2(delta.y, delta.x);
  5297. return new Angle(theta);
  5298. };
  5299. /**
  5300. * Returns a new Angle object from the passed float in radians.
  5301. */
  5302. Angle.FromRadians = function (radians) {
  5303. return new Angle(radians);
  5304. };
  5305. /**
  5306. * Returns a new Angle object from the passed float in degrees.
  5307. */
  5308. Angle.FromDegrees = function (degrees) {
  5309. return new Angle(degrees * Math.PI / 180.0);
  5310. };
  5311. return Angle;
  5312. }());
  5313. BABYLON.Angle = Angle;
  5314. var Arc2 = /** @class */ (function () {
  5315. /**
  5316. * Creates an Arc object from the three passed points : start, middle and end.
  5317. */
  5318. function Arc2(startPoint, midPoint, endPoint) {
  5319. this.startPoint = startPoint;
  5320. this.midPoint = midPoint;
  5321. this.endPoint = endPoint;
  5322. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5323. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5324. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5325. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5326. 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);
  5327. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5328. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5329. var a1 = this.startAngle.degrees();
  5330. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5331. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5332. // angles correction
  5333. if (a2 - a1 > +180.0)
  5334. a2 -= 360.0;
  5335. if (a2 - a1 < -180.0)
  5336. a2 += 360.0;
  5337. if (a3 - a2 > +180.0)
  5338. a3 -= 360.0;
  5339. if (a3 - a2 < -180.0)
  5340. a3 += 360.0;
  5341. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5342. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5343. }
  5344. return Arc2;
  5345. }());
  5346. BABYLON.Arc2 = Arc2;
  5347. var Path2 = /** @class */ (function () {
  5348. /**
  5349. * Creates a Path2 object from the starting 2D coordinates x and y.
  5350. */
  5351. function Path2(x, y) {
  5352. this._points = new Array();
  5353. this._length = 0.0;
  5354. this.closed = false;
  5355. this._points.push(new Vector2(x, y));
  5356. }
  5357. /**
  5358. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5359. * Returns the updated Path2.
  5360. */
  5361. Path2.prototype.addLineTo = function (x, y) {
  5362. if (this.closed) {
  5363. //Tools.Error("cannot add lines to closed paths");
  5364. return this;
  5365. }
  5366. var newPoint = new Vector2(x, y);
  5367. var previousPoint = this._points[this._points.length - 1];
  5368. this._points.push(newPoint);
  5369. this._length += newPoint.subtract(previousPoint).length();
  5370. return this;
  5371. };
  5372. /**
  5373. * 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.
  5374. * Returns the updated Path2.
  5375. */
  5376. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5377. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5378. if (this.closed) {
  5379. //Tools.Error("cannot add arcs to closed paths");
  5380. return this;
  5381. }
  5382. var startPoint = this._points[this._points.length - 1];
  5383. var midPoint = new Vector2(midX, midY);
  5384. var endPoint = new Vector2(endX, endY);
  5385. var arc = new Arc2(startPoint, midPoint, endPoint);
  5386. var increment = arc.angle.radians() / numberOfSegments;
  5387. if (arc.orientation === Orientation.CW)
  5388. increment *= -1;
  5389. var currentAngle = arc.startAngle.radians() + increment;
  5390. for (var i = 0; i < numberOfSegments; i++) {
  5391. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5392. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5393. this.addLineTo(x, y);
  5394. currentAngle += increment;
  5395. }
  5396. return this;
  5397. };
  5398. /**
  5399. * Closes the Path2.
  5400. * Returns the Path2.
  5401. */
  5402. Path2.prototype.close = function () {
  5403. this.closed = true;
  5404. return this;
  5405. };
  5406. /**
  5407. * Returns the Path2 total length (float).
  5408. */
  5409. Path2.prototype.length = function () {
  5410. var result = this._length;
  5411. if (!this.closed) {
  5412. var lastPoint = this._points[this._points.length - 1];
  5413. var firstPoint = this._points[0];
  5414. result += (firstPoint.subtract(lastPoint).length());
  5415. }
  5416. return result;
  5417. };
  5418. /**
  5419. * Returns the Path2 internal array of points.
  5420. */
  5421. Path2.prototype.getPoints = function () {
  5422. return this._points;
  5423. };
  5424. /**
  5425. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5426. */
  5427. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5428. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5429. //Tools.Error("normalized length position should be between 0 and 1.");
  5430. return Vector2.Zero();
  5431. }
  5432. var lengthPosition = normalizedLengthPosition * this.length();
  5433. var previousOffset = 0;
  5434. for (var i = 0; i < this._points.length; i++) {
  5435. var j = (i + 1) % this._points.length;
  5436. var a = this._points[i];
  5437. var b = this._points[j];
  5438. var bToA = b.subtract(a);
  5439. var nextOffset = (bToA.length() + previousOffset);
  5440. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5441. var dir = bToA.normalize();
  5442. var localOffset = lengthPosition - previousOffset;
  5443. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5444. }
  5445. previousOffset = nextOffset;
  5446. }
  5447. //Tools.Error("internal error");
  5448. return Vector2.Zero();
  5449. };
  5450. /**
  5451. * Returns a new Path2 starting at the coordinates (x, y).
  5452. */
  5453. Path2.StartingAt = function (x, y) {
  5454. return new Path2(x, y);
  5455. };
  5456. return Path2;
  5457. }());
  5458. BABYLON.Path2 = Path2;
  5459. var Path3D = /** @class */ (function () {
  5460. /**
  5461. * new Path3D(path, normal, raw)
  5462. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5463. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5464. * path : an array of Vector3, the curve axis of the Path3D
  5465. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5466. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5467. */
  5468. function Path3D(path, firstNormal, raw) {
  5469. if (firstNormal === void 0) { firstNormal = null; }
  5470. this.path = path;
  5471. this._curve = new Array();
  5472. this._distances = new Array();
  5473. this._tangents = new Array();
  5474. this._normals = new Array();
  5475. this._binormals = new Array();
  5476. for (var p = 0; p < path.length; p++) {
  5477. this._curve[p] = path[p].clone(); // hard copy
  5478. }
  5479. this._raw = raw || false;
  5480. this._compute(firstNormal);
  5481. }
  5482. /**
  5483. * Returns the Path3D array of successive Vector3 designing its curve.
  5484. */
  5485. Path3D.prototype.getCurve = function () {
  5486. return this._curve;
  5487. };
  5488. /**
  5489. * Returns an array populated with tangent vectors on each Path3D curve point.
  5490. */
  5491. Path3D.prototype.getTangents = function () {
  5492. return this._tangents;
  5493. };
  5494. /**
  5495. * Returns an array populated with normal vectors on each Path3D curve point.
  5496. */
  5497. Path3D.prototype.getNormals = function () {
  5498. return this._normals;
  5499. };
  5500. /**
  5501. * Returns an array populated with binormal vectors on each Path3D curve point.
  5502. */
  5503. Path3D.prototype.getBinormals = function () {
  5504. return this._binormals;
  5505. };
  5506. /**
  5507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5508. */
  5509. Path3D.prototype.getDistances = function () {
  5510. return this._distances;
  5511. };
  5512. /**
  5513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5514. * Returns the same object updated.
  5515. */
  5516. Path3D.prototype.update = function (path, firstNormal) {
  5517. if (firstNormal === void 0) { firstNormal = null; }
  5518. for (var p = 0; p < path.length; p++) {
  5519. this._curve[p].x = path[p].x;
  5520. this._curve[p].y = path[p].y;
  5521. this._curve[p].z = path[p].z;
  5522. }
  5523. this._compute(firstNormal);
  5524. return this;
  5525. };
  5526. // private function compute() : computes tangents, normals and binormals
  5527. Path3D.prototype._compute = function (firstNormal) {
  5528. var l = this._curve.length;
  5529. // first and last tangents
  5530. this._tangents[0] = this._getFirstNonNullVector(0);
  5531. if (!this._raw) {
  5532. this._tangents[0].normalize();
  5533. }
  5534. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5535. if (!this._raw) {
  5536. this._tangents[l - 1].normalize();
  5537. }
  5538. // normals and binormals at first point : arbitrary vector with _normalVector()
  5539. var tg0 = this._tangents[0];
  5540. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5541. this._normals[0] = pp0;
  5542. if (!this._raw) {
  5543. this._normals[0].normalize();
  5544. }
  5545. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5546. if (!this._raw) {
  5547. this._binormals[0].normalize();
  5548. }
  5549. this._distances[0] = 0.0;
  5550. // normals and binormals : next points
  5551. var prev; // previous vector (segment)
  5552. var cur; // current vector (segment)
  5553. var curTang; // current tangent
  5554. // previous normal
  5555. var prevBinor; // previous binormal
  5556. for (var i = 1; i < l; i++) {
  5557. // tangents
  5558. prev = this._getLastNonNullVector(i);
  5559. if (i < l - 1) {
  5560. cur = this._getFirstNonNullVector(i);
  5561. this._tangents[i] = prev.add(cur);
  5562. this._tangents[i].normalize();
  5563. }
  5564. this._distances[i] = this._distances[i - 1] + prev.length();
  5565. // normals and binormals
  5566. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5567. curTang = this._tangents[i];
  5568. prevBinor = this._binormals[i - 1];
  5569. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5570. if (!this._raw) {
  5571. this._normals[i].normalize();
  5572. }
  5573. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5574. if (!this._raw) {
  5575. this._binormals[i].normalize();
  5576. }
  5577. }
  5578. };
  5579. // private function getFirstNonNullVector(index)
  5580. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5581. Path3D.prototype._getFirstNonNullVector = function (index) {
  5582. var i = 1;
  5583. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5584. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5585. i++;
  5586. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5587. }
  5588. return nNVector;
  5589. };
  5590. // private function getLastNonNullVector(index)
  5591. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5592. Path3D.prototype._getLastNonNullVector = function (index) {
  5593. var i = 1;
  5594. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5595. while (nLVector.length() === 0 && index > i + 1) {
  5596. i++;
  5597. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5598. }
  5599. return nLVector;
  5600. };
  5601. // private function normalVector(v0, vt, va) :
  5602. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5603. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5604. Path3D.prototype._normalVector = function (v0, vt, va) {
  5605. var normal0;
  5606. var tgl = vt.length();
  5607. if (tgl === 0.0) {
  5608. tgl = 1.0;
  5609. }
  5610. if (va === undefined || va === null) {
  5611. var point;
  5612. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5613. point = new Vector3(0.0, -1.0, 0.0);
  5614. }
  5615. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5616. point = new Vector3(1.0, 0.0, 0.0);
  5617. }
  5618. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5619. point = new Vector3(0.0, 0.0, 1.0);
  5620. }
  5621. else {
  5622. point = Vector3.Zero();
  5623. }
  5624. normal0 = Vector3.Cross(vt, point);
  5625. }
  5626. else {
  5627. normal0 = Vector3.Cross(vt, va);
  5628. Vector3.CrossToRef(normal0, vt, normal0);
  5629. }
  5630. normal0.normalize();
  5631. return normal0;
  5632. };
  5633. return Path3D;
  5634. }());
  5635. BABYLON.Path3D = Path3D;
  5636. var Curve3 = /** @class */ (function () {
  5637. /**
  5638. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5639. * A Curve3 is designed from a series of successive Vector3.
  5640. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5641. */
  5642. function Curve3(points) {
  5643. this._length = 0.0;
  5644. this._points = points;
  5645. this._length = this._computeLength(points);
  5646. }
  5647. /**
  5648. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5649. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5650. * @param v1 (Vector3) the control point
  5651. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5652. * @param nbPoints (integer) the wanted number of points in the curve
  5653. */
  5654. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5655. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5656. var bez = new Array();
  5657. var equation = function (t, val0, val1, val2) {
  5658. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5659. return res;
  5660. };
  5661. for (var i = 0; i <= nbPoints; i++) {
  5662. 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)));
  5663. }
  5664. return new Curve3(bez);
  5665. };
  5666. /**
  5667. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5668. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5669. * @param v1 (Vector3) the first control point
  5670. * @param v2 (Vector3) the second control point
  5671. * @param v3 (Vector3) the end point of the Cubic Bezier
  5672. * @param nbPoints (integer) the wanted number of points in the curve
  5673. */
  5674. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5675. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5676. var bez = new Array();
  5677. var equation = function (t, val0, val1, val2, val3) {
  5678. 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;
  5679. return res;
  5680. };
  5681. for (var i = 0; i <= nbPoints; i++) {
  5682. 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)));
  5683. }
  5684. return new Curve3(bez);
  5685. };
  5686. /**
  5687. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5688. * @param p1 (Vector3) the origin point of the Hermite Spline
  5689. * @param t1 (Vector3) the tangent vector at the origin point
  5690. * @param p2 (Vector3) the end point of the Hermite Spline
  5691. * @param t2 (Vector3) the tangent vector at the end point
  5692. * @param nbPoints (integer) the wanted number of points in the curve
  5693. */
  5694. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5695. var hermite = new Array();
  5696. var step = 1.0 / nbPoints;
  5697. for (var i = 0; i <= nbPoints; i++) {
  5698. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5699. }
  5700. return new Curve3(hermite);
  5701. };
  5702. /**
  5703. * Returns a Curve3 object along a CatmullRom Spline curve :
  5704. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5705. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5706. */
  5707. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5708. var totalPoints = new Array();
  5709. totalPoints.push(points[0].clone());
  5710. Array.prototype.push.apply(totalPoints, points);
  5711. totalPoints.push(points[points.length - 1].clone());
  5712. var catmullRom = new Array();
  5713. var step = 1.0 / nbPoints;
  5714. var amount = 0.0;
  5715. for (var i = 0; i < totalPoints.length - 3; i++) {
  5716. amount = 0;
  5717. for (var c = 0; c < nbPoints; c++) {
  5718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5719. amount += step;
  5720. }
  5721. }
  5722. i--;
  5723. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5724. return new Curve3(catmullRom);
  5725. };
  5726. /**
  5727. * Returns the Curve3 stored array of successive Vector3
  5728. */
  5729. Curve3.prototype.getPoints = function () {
  5730. return this._points;
  5731. };
  5732. /**
  5733. * Returns the computed length (float) of the curve.
  5734. */
  5735. Curve3.prototype.length = function () {
  5736. return this._length;
  5737. };
  5738. /**
  5739. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5740. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5741. * curveA and curveB keep unchanged.
  5742. */
  5743. Curve3.prototype.continue = function (curve) {
  5744. var lastPoint = this._points[this._points.length - 1];
  5745. var continuedPoints = this._points.slice();
  5746. var curvePoints = curve.getPoints();
  5747. for (var i = 1; i < curvePoints.length; i++) {
  5748. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5749. }
  5750. var continuedCurve = new Curve3(continuedPoints);
  5751. return continuedCurve;
  5752. };
  5753. Curve3.prototype._computeLength = function (path) {
  5754. var l = 0;
  5755. for (var i = 1; i < path.length; i++) {
  5756. l += (path[i].subtract(path[i - 1])).length();
  5757. }
  5758. return l;
  5759. };
  5760. return Curve3;
  5761. }());
  5762. BABYLON.Curve3 = Curve3;
  5763. // Vertex formats
  5764. var PositionNormalVertex = /** @class */ (function () {
  5765. function PositionNormalVertex(position, normal) {
  5766. if (position === void 0) { position = Vector3.Zero(); }
  5767. if (normal === void 0) { normal = Vector3.Up(); }
  5768. this.position = position;
  5769. this.normal = normal;
  5770. }
  5771. PositionNormalVertex.prototype.clone = function () {
  5772. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5773. };
  5774. return PositionNormalVertex;
  5775. }());
  5776. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5777. var PositionNormalTextureVertex = /** @class */ (function () {
  5778. function PositionNormalTextureVertex(position, normal, uv) {
  5779. if (position === void 0) { position = Vector3.Zero(); }
  5780. if (normal === void 0) { normal = Vector3.Up(); }
  5781. if (uv === void 0) { uv = Vector2.Zero(); }
  5782. this.position = position;
  5783. this.normal = normal;
  5784. this.uv = uv;
  5785. }
  5786. PositionNormalTextureVertex.prototype.clone = function () {
  5787. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5788. };
  5789. return PositionNormalTextureVertex;
  5790. }());
  5791. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5792. // Temporary pre-allocated objects for engine internal use
  5793. // usage in any internal function :
  5794. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5795. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5796. var Tmp = /** @class */ (function () {
  5797. function Tmp() {
  5798. }
  5799. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5800. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5801. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5802. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5803. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5804. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5805. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5806. Matrix.Zero(), Matrix.Zero(),
  5807. Matrix.Zero(), Matrix.Zero(),
  5808. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5809. return Tmp;
  5810. }());
  5811. BABYLON.Tmp = Tmp;
  5812. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5813. var MathTmp = /** @class */ (function () {
  5814. function MathTmp() {
  5815. }
  5816. MathTmp.Vector3 = [Vector3.Zero()];
  5817. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5818. MathTmp.Quaternion = [Quaternion.Zero()];
  5819. return MathTmp;
  5820. }());
  5821. })(BABYLON || (BABYLON = {}));
  5822. //# sourceMappingURL=babylon.math.js.map
  5823. var BABYLON;
  5824. (function (BABYLON) {
  5825. var Scalar = /** @class */ (function () {
  5826. function Scalar() {
  5827. }
  5828. /**
  5829. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5830. */
  5831. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5832. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5833. var num = a - b;
  5834. return -epsilon <= num && num <= epsilon;
  5835. };
  5836. /**
  5837. * Returns a string : the upper case translation of the number i to hexadecimal.
  5838. */
  5839. Scalar.ToHex = function (i) {
  5840. var str = i.toString(16);
  5841. if (i <= 15) {
  5842. return ("0" + str).toUpperCase();
  5843. }
  5844. return str.toUpperCase();
  5845. };
  5846. /**
  5847. * Returns -1 if value is negative and +1 is value is positive.
  5848. * Returns the value itself if it's equal to zero.
  5849. */
  5850. Scalar.Sign = function (value) {
  5851. value = +value; // convert to a number
  5852. if (value === 0 || isNaN(value))
  5853. return value;
  5854. return value > 0 ? 1 : -1;
  5855. };
  5856. /**
  5857. * Returns the value itself if it's between min and max.
  5858. * Returns min if the value is lower than min.
  5859. * Returns max if the value is greater than max.
  5860. */
  5861. Scalar.Clamp = function (value, min, max) {
  5862. if (min === void 0) { min = 0; }
  5863. if (max === void 0) { max = 1; }
  5864. return Math.min(max, Math.max(min, value));
  5865. };
  5866. /**
  5867. * Returns the log2 of value.
  5868. */
  5869. Scalar.Log2 = function (value) {
  5870. return Math.log(value) * Math.LOG2E;
  5871. };
  5872. /**
  5873. * Loops the value, so that it is never larger than length and never smaller than 0.
  5874. *
  5875. * This is similar to the modulo operator but it works with floating point numbers.
  5876. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5877. * With t = 5 and length = 2.5, the result would be 0.0.
  5878. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5879. */
  5880. Scalar.Repeat = function (value, length) {
  5881. return value - Math.floor(value / length) * length;
  5882. };
  5883. /**
  5884. * Normalize the value between 0.0 and 1.0 using min and max values
  5885. */
  5886. Scalar.Normalize = function (value, min, max) {
  5887. return (value - min) / (max - min);
  5888. };
  5889. /**
  5890. * Denormalize the value from 0.0 and 1.0 using min and max values
  5891. */
  5892. Scalar.Denormalize = function (normalized, min, max) {
  5893. return (normalized * (max - min) + min);
  5894. };
  5895. /**
  5896. * Calculates the shortest difference between two given angles given in degrees.
  5897. */
  5898. Scalar.DeltaAngle = function (current, target) {
  5899. var num = Scalar.Repeat(target - current, 360.0);
  5900. if (num > 180.0) {
  5901. num -= 360.0;
  5902. }
  5903. return num;
  5904. };
  5905. /**
  5906. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5907. *
  5908. * The returned value will move back and forth between 0 and length
  5909. */
  5910. Scalar.PingPong = function (tx, length) {
  5911. var t = Scalar.Repeat(tx, length * 2.0);
  5912. return length - Math.abs(t - length);
  5913. };
  5914. /**
  5915. * Interpolates between min and max with smoothing at the limits.
  5916. *
  5917. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5918. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5919. */
  5920. Scalar.SmoothStep = function (from, to, tx) {
  5921. var t = Scalar.Clamp(tx);
  5922. t = -2.0 * t * t * t + 3.0 * t * t;
  5923. return to * t + from * (1.0 - t);
  5924. };
  5925. /**
  5926. * Moves a value current towards target.
  5927. *
  5928. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5929. * Negative values of maxDelta pushes the value away from target.
  5930. */
  5931. Scalar.MoveTowards = function (current, target, maxDelta) {
  5932. var result = 0;
  5933. if (Math.abs(target - current) <= maxDelta) {
  5934. result = target;
  5935. }
  5936. else {
  5937. result = current + Scalar.Sign(target - current) * maxDelta;
  5938. }
  5939. return result;
  5940. };
  5941. /**
  5942. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5943. *
  5944. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5945. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5946. */
  5947. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5948. var num = Scalar.DeltaAngle(current, target);
  5949. var result = 0;
  5950. if (-maxDelta < num && num < maxDelta) {
  5951. result = target;
  5952. }
  5953. else {
  5954. target = current + num;
  5955. result = Scalar.MoveTowards(current, target, maxDelta);
  5956. }
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5961. */
  5962. Scalar.Lerp = function (start, end, amount) {
  5963. return start + ((end - start) * amount);
  5964. };
  5965. /**
  5966. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5967. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5968. */
  5969. Scalar.LerpAngle = function (start, end, amount) {
  5970. var num = Scalar.Repeat(end - start, 360.0);
  5971. if (num > 180.0) {
  5972. num -= 360.0;
  5973. }
  5974. return start + num * Scalar.Clamp(amount);
  5975. };
  5976. /**
  5977. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5978. */
  5979. Scalar.InverseLerp = function (a, b, value) {
  5980. var result = 0;
  5981. if (a != b) {
  5982. result = Scalar.Clamp((value - a) / (b - a));
  5983. }
  5984. else {
  5985. result = 0.0;
  5986. }
  5987. return result;
  5988. };
  5989. /**
  5990. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5991. */
  5992. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5993. var squared = amount * amount;
  5994. var cubed = amount * squared;
  5995. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5996. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5997. var part3 = (cubed - (2.0 * squared)) + amount;
  5998. var part4 = cubed - squared;
  5999. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6000. };
  6001. /**
  6002. * Returns a random float number between and min and max values
  6003. */
  6004. Scalar.RandomRange = function (min, max) {
  6005. if (min === max)
  6006. return min;
  6007. return ((Math.random() * (max - min)) + min);
  6008. };
  6009. /**
  6010. * This function returns percentage of a number in a given range.
  6011. *
  6012. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6013. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6014. */
  6015. Scalar.RangeToPercent = function (number, min, max) {
  6016. return ((number - min) / (max - min));
  6017. };
  6018. /**
  6019. * This function returns number that corresponds to the percentage in a given range.
  6020. *
  6021. * PercentToRange(0.34,0,100) will return 34.
  6022. */
  6023. Scalar.PercentToRange = function (percent, min, max) {
  6024. return ((max - min) * percent + min);
  6025. };
  6026. /**
  6027. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6028. * @param angle The angle to normalize in radian.
  6029. * @return The converted angle.
  6030. */
  6031. Scalar.NormalizeRadians = function (angle) {
  6032. // More precise but slower version kept for reference.
  6033. // angle = angle % Tools.TwoPi;
  6034. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6035. //if (angle > Math.PI) {
  6036. // angle -= Tools.TwoPi;
  6037. //}
  6038. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6039. return angle;
  6040. };
  6041. /**
  6042. * Two pi constants convenient for computation.
  6043. */
  6044. Scalar.TwoPi = Math.PI * 2;
  6045. return Scalar;
  6046. }());
  6047. BABYLON.Scalar = Scalar;
  6048. })(BABYLON || (BABYLON = {}));
  6049. //# sourceMappingURL=babylon.math.scalar.js.map
  6050. //# sourceMappingURL=babylon.mixins.js.map
  6051. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6052. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6053. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6054. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6055. //# sourceMappingURL=babylon.webgl2.js.map
  6056. var BABYLON;
  6057. (function (BABYLON) {
  6058. var __decoratorInitialStore = {};
  6059. var __mergedStore = {};
  6060. var _copySource = function (creationFunction, source, instanciate) {
  6061. var destination = creationFunction();
  6062. // Tags
  6063. if (BABYLON.Tags) {
  6064. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6065. }
  6066. var classStore = getMergedStore(destination);
  6067. // Properties
  6068. for (var property in classStore) {
  6069. var propertyDescriptor = classStore[property];
  6070. var sourceProperty = source[property];
  6071. var propertyType = propertyDescriptor.type;
  6072. if (sourceProperty !== undefined && sourceProperty !== null) {
  6073. switch (propertyType) {
  6074. case 0: // Value
  6075. case 6:// Mesh reference
  6076. destination[property] = sourceProperty;
  6077. break;
  6078. case 1:// Texture
  6079. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6080. break;
  6081. case 2: // Color3
  6082. case 3: // FresnelParameters
  6083. case 4: // Vector2
  6084. case 5: // Vector3
  6085. case 7: // Color Curves
  6086. case 10:// Quaternion
  6087. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6088. break;
  6089. }
  6090. }
  6091. }
  6092. return destination;
  6093. };
  6094. function getDirectStore(target) {
  6095. var classKey = target.getClassName();
  6096. if (!__decoratorInitialStore[classKey]) {
  6097. __decoratorInitialStore[classKey] = {};
  6098. }
  6099. return __decoratorInitialStore[classKey];
  6100. }
  6101. /**
  6102. * Return the list of properties flagged as serializable
  6103. * @param target: host object
  6104. */
  6105. function getMergedStore(target) {
  6106. var classKey = target.getClassName();
  6107. if (__mergedStore[classKey]) {
  6108. return __mergedStore[classKey];
  6109. }
  6110. __mergedStore[classKey] = {};
  6111. var store = __mergedStore[classKey];
  6112. var currentTarget = target;
  6113. var currentKey = classKey;
  6114. while (currentKey) {
  6115. var initialStore = __decoratorInitialStore[currentKey];
  6116. for (var property in initialStore) {
  6117. store[property] = initialStore[property];
  6118. }
  6119. var parent_1 = void 0;
  6120. var done = false;
  6121. do {
  6122. parent_1 = Object.getPrototypeOf(currentTarget);
  6123. if (!parent_1.getClassName) {
  6124. done = true;
  6125. break;
  6126. }
  6127. if (parent_1.getClassName() !== currentKey) {
  6128. break;
  6129. }
  6130. currentTarget = parent_1;
  6131. } while (parent_1);
  6132. if (done) {
  6133. break;
  6134. }
  6135. currentKey = parent_1.getClassName();
  6136. currentTarget = parent_1;
  6137. }
  6138. return store;
  6139. }
  6140. function generateSerializableMember(type, sourceName) {
  6141. return function (target, propertyKey) {
  6142. var classStore = getDirectStore(target);
  6143. if (!classStore[propertyKey]) {
  6144. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6145. }
  6146. };
  6147. }
  6148. function generateExpandMember(setCallback, targetKey) {
  6149. if (targetKey === void 0) { targetKey = null; }
  6150. return function (target, propertyKey) {
  6151. var key = targetKey || ("_" + propertyKey);
  6152. Object.defineProperty(target, propertyKey, {
  6153. get: function () {
  6154. return this[key];
  6155. },
  6156. set: function (value) {
  6157. if (this[key] === value) {
  6158. return;
  6159. }
  6160. this[key] = value;
  6161. target[setCallback].apply(this);
  6162. },
  6163. enumerable: true,
  6164. configurable: true
  6165. });
  6166. };
  6167. }
  6168. function expandToProperty(callback, targetKey) {
  6169. if (targetKey === void 0) { targetKey = null; }
  6170. return generateExpandMember(callback, targetKey);
  6171. }
  6172. BABYLON.expandToProperty = expandToProperty;
  6173. function serialize(sourceName) {
  6174. return generateSerializableMember(0, sourceName); // value member
  6175. }
  6176. BABYLON.serialize = serialize;
  6177. function serializeAsTexture(sourceName) {
  6178. return generateSerializableMember(1, sourceName); // texture member
  6179. }
  6180. BABYLON.serializeAsTexture = serializeAsTexture;
  6181. function serializeAsColor3(sourceName) {
  6182. return generateSerializableMember(2, sourceName); // color3 member
  6183. }
  6184. BABYLON.serializeAsColor3 = serializeAsColor3;
  6185. function serializeAsFresnelParameters(sourceName) {
  6186. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6187. }
  6188. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6189. function serializeAsVector2(sourceName) {
  6190. return generateSerializableMember(4, sourceName); // vector2 member
  6191. }
  6192. BABYLON.serializeAsVector2 = serializeAsVector2;
  6193. function serializeAsVector3(sourceName) {
  6194. return generateSerializableMember(5, sourceName); // vector3 member
  6195. }
  6196. BABYLON.serializeAsVector3 = serializeAsVector3;
  6197. function serializeAsMeshReference(sourceName) {
  6198. return generateSerializableMember(6, sourceName); // mesh reference member
  6199. }
  6200. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6201. function serializeAsColorCurves(sourceName) {
  6202. return generateSerializableMember(7, sourceName); // color curves
  6203. }
  6204. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6205. function serializeAsColor4(sourceName) {
  6206. return generateSerializableMember(8, sourceName); // color 4
  6207. }
  6208. BABYLON.serializeAsColor4 = serializeAsColor4;
  6209. function serializeAsImageProcessingConfiguration(sourceName) {
  6210. return generateSerializableMember(9, sourceName); // image processing
  6211. }
  6212. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6213. function serializeAsQuaternion(sourceName) {
  6214. return generateSerializableMember(10, sourceName); // quaternion member
  6215. }
  6216. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6217. var SerializationHelper = /** @class */ (function () {
  6218. function SerializationHelper() {
  6219. }
  6220. SerializationHelper.Serialize = function (entity, serializationObject) {
  6221. if (!serializationObject) {
  6222. serializationObject = {};
  6223. }
  6224. // Tags
  6225. if (BABYLON.Tags) {
  6226. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6227. }
  6228. var serializedProperties = getMergedStore(entity);
  6229. // Properties
  6230. for (var property in serializedProperties) {
  6231. var propertyDescriptor = serializedProperties[property];
  6232. var targetPropertyName = propertyDescriptor.sourceName || property;
  6233. var propertyType = propertyDescriptor.type;
  6234. var sourceProperty = entity[property];
  6235. if (sourceProperty !== undefined && sourceProperty !== null) {
  6236. switch (propertyType) {
  6237. case 0:// Value
  6238. serializationObject[targetPropertyName] = sourceProperty;
  6239. break;
  6240. case 1:// Texture
  6241. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6242. break;
  6243. case 2:// Color3
  6244. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6245. break;
  6246. case 3:// FresnelParameters
  6247. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6248. break;
  6249. case 4:// Vector2
  6250. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6251. break;
  6252. case 5:// Vector3
  6253. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6254. break;
  6255. case 6:// Mesh reference
  6256. serializationObject[targetPropertyName] = sourceProperty.id;
  6257. break;
  6258. case 7:// Color Curves
  6259. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6260. break;
  6261. case 8:// Color 4
  6262. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6263. break;
  6264. case 9:// Image Processing
  6265. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6266. break;
  6267. }
  6268. }
  6269. }
  6270. return serializationObject;
  6271. };
  6272. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6273. if (rootUrl === void 0) { rootUrl = null; }
  6274. var destination = creationFunction();
  6275. if (!rootUrl) {
  6276. rootUrl = "";
  6277. }
  6278. // Tags
  6279. if (BABYLON.Tags) {
  6280. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6281. }
  6282. var classStore = getMergedStore(destination);
  6283. // Properties
  6284. for (var property in classStore) {
  6285. var propertyDescriptor = classStore[property];
  6286. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6287. var propertyType = propertyDescriptor.type;
  6288. if (sourceProperty !== undefined && sourceProperty !== null) {
  6289. var dest = destination;
  6290. switch (propertyType) {
  6291. case 0:// Value
  6292. dest[property] = sourceProperty;
  6293. break;
  6294. case 1:// Texture
  6295. if (scene) {
  6296. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6297. }
  6298. break;
  6299. case 2:// Color3
  6300. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6301. break;
  6302. case 3:// FresnelParameters
  6303. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6304. break;
  6305. case 4:// Vector2
  6306. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6307. break;
  6308. case 5:// Vector3
  6309. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6310. break;
  6311. case 6:// Mesh reference
  6312. if (scene) {
  6313. dest[property] = scene.getLastMeshByID(sourceProperty);
  6314. }
  6315. break;
  6316. case 7:// Color Curves
  6317. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6318. break;
  6319. case 8:// Color 4
  6320. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6321. break;
  6322. case 9:// Image Processing
  6323. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6324. break;
  6325. }
  6326. }
  6327. }
  6328. return destination;
  6329. };
  6330. SerializationHelper.Clone = function (creationFunction, source) {
  6331. return _copySource(creationFunction, source, false);
  6332. };
  6333. SerializationHelper.Instanciate = function (creationFunction, source) {
  6334. return _copySource(creationFunction, source, true);
  6335. };
  6336. return SerializationHelper;
  6337. }());
  6338. BABYLON.SerializationHelper = SerializationHelper;
  6339. })(BABYLON || (BABYLON = {}));
  6340. //# sourceMappingURL=babylon.decorators.js.map
  6341. var BABYLON;
  6342. (function (BABYLON) {
  6343. /**
  6344. * A class serves as a medium between the observable and its observers
  6345. */
  6346. var EventState = /** @class */ (function () {
  6347. /**
  6348. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6349. */
  6350. function EventState(mask, skipNextObservers, target, currentTarget) {
  6351. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6352. this.initalize(mask, skipNextObservers, target, currentTarget);
  6353. }
  6354. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6355. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6356. this.mask = mask;
  6357. this.skipNextObservers = skipNextObservers;
  6358. this.target = target;
  6359. this.currentTarget = currentTarget;
  6360. return this;
  6361. };
  6362. return EventState;
  6363. }());
  6364. BABYLON.EventState = EventState;
  6365. /**
  6366. * Represent an Observer registered to a given Observable object.
  6367. */
  6368. var Observer = /** @class */ (function () {
  6369. function Observer(callback, mask, scope) {
  6370. if (scope === void 0) { scope = null; }
  6371. this.callback = callback;
  6372. this.mask = mask;
  6373. this.scope = scope;
  6374. }
  6375. return Observer;
  6376. }());
  6377. BABYLON.Observer = Observer;
  6378. /**
  6379. * Represent a list of observers registered to multiple Observables object.
  6380. */
  6381. var MultiObserver = /** @class */ (function () {
  6382. function MultiObserver() {
  6383. }
  6384. MultiObserver.prototype.dispose = function () {
  6385. if (this._observers && this._observables) {
  6386. for (var index = 0; index < this._observers.length; index++) {
  6387. this._observables[index].remove(this._observers[index]);
  6388. }
  6389. }
  6390. this._observers = null;
  6391. this._observables = null;
  6392. };
  6393. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6394. if (mask === void 0) { mask = -1; }
  6395. if (scope === void 0) { scope = null; }
  6396. var result = new MultiObserver();
  6397. result._observers = new Array();
  6398. result._observables = observables;
  6399. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6400. var observable = observables_1[_i];
  6401. var observer = observable.add(callback, mask, false, scope);
  6402. if (observer) {
  6403. result._observers.push(observer);
  6404. }
  6405. }
  6406. return result;
  6407. };
  6408. return MultiObserver;
  6409. }());
  6410. BABYLON.MultiObserver = MultiObserver;
  6411. /**
  6412. * The Observable class is a simple implementation of the Observable pattern.
  6413. * 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.
  6414. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6415. * 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).
  6416. * 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.
  6417. */
  6418. var Observable = /** @class */ (function () {
  6419. function Observable(onObserverAdded) {
  6420. this._observers = new Array();
  6421. this._eventState = new EventState(0);
  6422. if (onObserverAdded) {
  6423. this._onObserverAdded = onObserverAdded;
  6424. }
  6425. }
  6426. /**
  6427. * Create a new Observer with the specified callback
  6428. * @param callback the callback that will be executed for that Observer
  6429. * @param mask the mask used to filter observers
  6430. * @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.
  6431. * @param scope optional scope for the callback to be called from
  6432. */
  6433. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6434. if (mask === void 0) { mask = -1; }
  6435. if (insertFirst === void 0) { insertFirst = false; }
  6436. if (scope === void 0) { scope = null; }
  6437. if (!callback) {
  6438. return null;
  6439. }
  6440. var observer = new Observer(callback, mask, scope);
  6441. if (insertFirst) {
  6442. this._observers.unshift(observer);
  6443. }
  6444. else {
  6445. this._observers.push(observer);
  6446. }
  6447. if (this._onObserverAdded) {
  6448. this._onObserverAdded(observer);
  6449. }
  6450. return observer;
  6451. };
  6452. /**
  6453. * Remove an Observer from the Observable object
  6454. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6455. */
  6456. Observable.prototype.remove = function (observer) {
  6457. if (!observer) {
  6458. return false;
  6459. }
  6460. var index = this._observers.indexOf(observer);
  6461. if (index !== -1) {
  6462. this._observers.splice(index, 1);
  6463. return true;
  6464. }
  6465. return false;
  6466. };
  6467. /**
  6468. * Remove a callback from the Observable object
  6469. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6470. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6471. */
  6472. Observable.prototype.removeCallback = function (callback, scope) {
  6473. for (var index = 0; index < this._observers.length; index++) {
  6474. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6475. this._observers.splice(index, 1);
  6476. return true;
  6477. }
  6478. }
  6479. return false;
  6480. };
  6481. /**
  6482. * Notify all Observers by calling their respective callback with the given data
  6483. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6484. * @param eventData
  6485. * @param mask
  6486. */
  6487. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6488. if (mask === void 0) { mask = -1; }
  6489. if (!this._observers.length) {
  6490. return true;
  6491. }
  6492. var state = this._eventState;
  6493. state.mask = mask;
  6494. state.target = target;
  6495. state.currentTarget = currentTarget;
  6496. state.skipNextObservers = false;
  6497. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6498. var obs = _a[_i];
  6499. if (obs.mask & mask) {
  6500. if (obs.scope) {
  6501. obs.callback.apply(obs.scope, [eventData, state]);
  6502. }
  6503. else {
  6504. obs.callback(eventData, state);
  6505. }
  6506. }
  6507. if (state.skipNextObservers) {
  6508. return false;
  6509. }
  6510. }
  6511. return true;
  6512. };
  6513. /**
  6514. * Notify a specific observer
  6515. * @param eventData
  6516. * @param mask
  6517. */
  6518. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6519. if (mask === void 0) { mask = -1; }
  6520. var state = this._eventState;
  6521. state.mask = mask;
  6522. state.skipNextObservers = false;
  6523. observer.callback(eventData, state);
  6524. };
  6525. /**
  6526. * return true is the Observable has at least one Observer registered
  6527. */
  6528. Observable.prototype.hasObservers = function () {
  6529. return this._observers.length > 0;
  6530. };
  6531. /**
  6532. * Clear the list of observers
  6533. */
  6534. Observable.prototype.clear = function () {
  6535. this._observers = new Array();
  6536. this._onObserverAdded = null;
  6537. };
  6538. /**
  6539. * Clone the current observable
  6540. */
  6541. Observable.prototype.clone = function () {
  6542. var result = new Observable();
  6543. result._observers = this._observers.slice(0);
  6544. return result;
  6545. };
  6546. /**
  6547. * Does this observable handles observer registered with a given mask
  6548. * @param {number} trigger - the mask to be tested
  6549. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6550. **/
  6551. Observable.prototype.hasSpecificMask = function (mask) {
  6552. if (mask === void 0) { mask = -1; }
  6553. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6554. var obs = _a[_i];
  6555. if (obs.mask & mask || obs.mask === mask) {
  6556. return true;
  6557. }
  6558. }
  6559. return false;
  6560. };
  6561. return Observable;
  6562. }());
  6563. BABYLON.Observable = Observable;
  6564. })(BABYLON || (BABYLON = {}));
  6565. //# sourceMappingURL=babylon.observable.js.map
  6566. var BABYLON;
  6567. (function (BABYLON) {
  6568. var SmartArray = /** @class */ (function () {
  6569. function SmartArray(capacity) {
  6570. this.length = 0;
  6571. this.data = new Array(capacity);
  6572. this._id = SmartArray._GlobalId++;
  6573. }
  6574. SmartArray.prototype.push = function (value) {
  6575. this.data[this.length++] = value;
  6576. if (this.length > this.data.length) {
  6577. this.data.length *= 2;
  6578. }
  6579. };
  6580. SmartArray.prototype.forEach = function (func) {
  6581. for (var index = 0; index < this.length; index++) {
  6582. func(this.data[index]);
  6583. }
  6584. };
  6585. SmartArray.prototype.sort = function (compareFn) {
  6586. this.data.sort(compareFn);
  6587. };
  6588. SmartArray.prototype.reset = function () {
  6589. this.length = 0;
  6590. };
  6591. SmartArray.prototype.dispose = function () {
  6592. this.reset();
  6593. if (this.data) {
  6594. this.data.length = 0;
  6595. this.data = [];
  6596. }
  6597. };
  6598. SmartArray.prototype.concat = function (array) {
  6599. if (array.length === 0) {
  6600. return;
  6601. }
  6602. if (this.length + array.length > this.data.length) {
  6603. this.data.length = (this.length + array.length) * 2;
  6604. }
  6605. for (var index = 0; index < array.length; index++) {
  6606. this.data[this.length++] = (array.data || array)[index];
  6607. }
  6608. };
  6609. SmartArray.prototype.indexOf = function (value) {
  6610. var position = this.data.indexOf(value);
  6611. if (position >= this.length) {
  6612. return -1;
  6613. }
  6614. return position;
  6615. };
  6616. SmartArray.prototype.contains = function (value) {
  6617. return this.data.indexOf(value) !== -1;
  6618. };
  6619. // Statics
  6620. SmartArray._GlobalId = 0;
  6621. return SmartArray;
  6622. }());
  6623. BABYLON.SmartArray = SmartArray;
  6624. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6625. __extends(SmartArrayNoDuplicate, _super);
  6626. function SmartArrayNoDuplicate() {
  6627. var _this = _super !== null && _super.apply(this, arguments) || this;
  6628. _this._duplicateId = 0;
  6629. return _this;
  6630. }
  6631. SmartArrayNoDuplicate.prototype.push = function (value) {
  6632. _super.prototype.push.call(this, value);
  6633. if (!value.__smartArrayFlags) {
  6634. value.__smartArrayFlags = {};
  6635. }
  6636. value.__smartArrayFlags[this._id] = this._duplicateId;
  6637. };
  6638. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6639. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6640. return false;
  6641. }
  6642. this.push(value);
  6643. return true;
  6644. };
  6645. SmartArrayNoDuplicate.prototype.reset = function () {
  6646. _super.prototype.reset.call(this);
  6647. this._duplicateId++;
  6648. };
  6649. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6650. if (array.length === 0) {
  6651. return;
  6652. }
  6653. if (this.length + array.length > this.data.length) {
  6654. this.data.length = (this.length + array.length) * 2;
  6655. }
  6656. for (var index = 0; index < array.length; index++) {
  6657. var item = (array.data || array)[index];
  6658. this.pushNoDuplicate(item);
  6659. }
  6660. };
  6661. return SmartArrayNoDuplicate;
  6662. }(SmartArray));
  6663. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6664. })(BABYLON || (BABYLON = {}));
  6665. //# sourceMappingURL=babylon.smartArray.js.map
  6666. var BABYLON;
  6667. (function (BABYLON) {
  6668. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6669. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6670. var LoadFileError = /** @class */ (function (_super) {
  6671. __extends(LoadFileError, _super);
  6672. function LoadFileError(message, request) {
  6673. var _this = _super.call(this, message) || this;
  6674. _this.request = request;
  6675. _this.name = "LoadFileError";
  6676. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6677. return _this;
  6678. }
  6679. // Polyfill for Object.setPrototypeOf if necessary.
  6680. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6681. return LoadFileError;
  6682. }(Error));
  6683. BABYLON.LoadFileError = LoadFileError;
  6684. var RetryStrategy = /** @class */ (function () {
  6685. function RetryStrategy() {
  6686. }
  6687. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6688. if (maxRetries === void 0) { maxRetries = 3; }
  6689. if (baseInterval === void 0) { baseInterval = 500; }
  6690. return function (url, request, retryIndex) {
  6691. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6692. return -1;
  6693. }
  6694. return Math.pow(2, retryIndex) * baseInterval;
  6695. };
  6696. };
  6697. return RetryStrategy;
  6698. }());
  6699. BABYLON.RetryStrategy = RetryStrategy;
  6700. // Screenshots
  6701. var screenshotCanvas;
  6702. var cloneValue = function (source, destinationObject) {
  6703. if (!source)
  6704. return null;
  6705. if (source instanceof BABYLON.Mesh) {
  6706. return null;
  6707. }
  6708. if (source instanceof BABYLON.SubMesh) {
  6709. return source.clone(destinationObject);
  6710. }
  6711. else if (source.clone) {
  6712. return source.clone();
  6713. }
  6714. return null;
  6715. };
  6716. var Tools = /** @class */ (function () {
  6717. function Tools() {
  6718. }
  6719. /**
  6720. * Interpolates between a and b via alpha
  6721. * @param a The lower value (returned when alpha = 0)
  6722. * @param b The upper value (returned when alpha = 1)
  6723. * @param alpha The interpolation-factor
  6724. * @return The mixed value
  6725. */
  6726. Tools.Mix = function (a, b, alpha) {
  6727. return a * (1 - alpha) + b * alpha;
  6728. };
  6729. Tools.Instantiate = function (className) {
  6730. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6731. return Tools.RegisteredExternalClasses[className];
  6732. }
  6733. var arr = className.split(".");
  6734. var fn = (window || this);
  6735. for (var i = 0, len = arr.length; i < len; i++) {
  6736. fn = fn[arr[i]];
  6737. }
  6738. if (typeof fn !== "function") {
  6739. return null;
  6740. }
  6741. return fn;
  6742. };
  6743. /**
  6744. * Provides a slice function that will work even on IE
  6745. * @param data defines the array to slice
  6746. * @returns the new sliced array
  6747. */
  6748. Tools.Slice = function (data) {
  6749. if (data.slice) {
  6750. return data.slice();
  6751. }
  6752. return Array.prototype.slice.call(data);
  6753. };
  6754. Tools.SetImmediate = function (action) {
  6755. if (window.setImmediate) {
  6756. window.setImmediate(action);
  6757. }
  6758. else {
  6759. setTimeout(action, 1);
  6760. }
  6761. };
  6762. Tools.IsExponentOfTwo = function (value) {
  6763. var count = 1;
  6764. do {
  6765. count *= 2;
  6766. } while (count < value);
  6767. return count === value;
  6768. };
  6769. /**
  6770. * Find the next highest power of two.
  6771. * @param x Number to start search from.
  6772. * @return Next highest power of two.
  6773. */
  6774. Tools.CeilingPOT = function (x) {
  6775. x--;
  6776. x |= x >> 1;
  6777. x |= x >> 2;
  6778. x |= x >> 4;
  6779. x |= x >> 8;
  6780. x |= x >> 16;
  6781. x++;
  6782. return x;
  6783. };
  6784. /**
  6785. * Find the next lowest power of two.
  6786. * @param x Number to start search from.
  6787. * @return Next lowest power of two.
  6788. */
  6789. Tools.FloorPOT = function (x) {
  6790. x = x | (x >> 1);
  6791. x = x | (x >> 2);
  6792. x = x | (x >> 4);
  6793. x = x | (x >> 8);
  6794. x = x | (x >> 16);
  6795. return x - (x >> 1);
  6796. };
  6797. /**
  6798. * Find the nearest power of two.
  6799. * @param x Number to start search from.
  6800. * @return Next nearest power of two.
  6801. */
  6802. Tools.NearestPOT = function (x) {
  6803. var c = Tools.CeilingPOT(x);
  6804. var f = Tools.FloorPOT(x);
  6805. return (c - x) > (x - f) ? f : c;
  6806. };
  6807. Tools.GetExponentOfTwo = function (value, max, mode) {
  6808. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6809. var pot;
  6810. switch (mode) {
  6811. case BABYLON.Engine.SCALEMODE_FLOOR:
  6812. pot = Tools.FloorPOT(value);
  6813. break;
  6814. case BABYLON.Engine.SCALEMODE_NEAREST:
  6815. pot = Tools.NearestPOT(value);
  6816. break;
  6817. case BABYLON.Engine.SCALEMODE_CEILING:
  6818. default:
  6819. pot = Tools.CeilingPOT(value);
  6820. break;
  6821. }
  6822. return Math.min(pot, max);
  6823. };
  6824. Tools.GetFilename = function (path) {
  6825. var index = path.lastIndexOf("/");
  6826. if (index < 0)
  6827. return path;
  6828. return path.substring(index + 1);
  6829. };
  6830. Tools.GetFolderPath = function (uri) {
  6831. var index = uri.lastIndexOf("/");
  6832. if (index < 0)
  6833. return "";
  6834. return uri.substring(0, index + 1);
  6835. };
  6836. Tools.GetDOMTextContent = function (element) {
  6837. var result = "";
  6838. var child = element.firstChild;
  6839. while (child) {
  6840. if (child.nodeType === 3) {
  6841. result += child.textContent;
  6842. }
  6843. child = child.nextSibling;
  6844. }
  6845. return result;
  6846. };
  6847. Tools.ToDegrees = function (angle) {
  6848. return angle * 180 / Math.PI;
  6849. };
  6850. Tools.ToRadians = function (angle) {
  6851. return angle * Math.PI / 180;
  6852. };
  6853. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6854. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6855. var output = "";
  6856. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6857. var i = 0;
  6858. var bytes = new Uint8Array(buffer);
  6859. while (i < bytes.length) {
  6860. chr1 = bytes[i++];
  6861. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6862. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6863. enc1 = chr1 >> 2;
  6864. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6865. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6866. enc4 = chr3 & 63;
  6867. if (isNaN(chr2)) {
  6868. enc3 = enc4 = 64;
  6869. }
  6870. else if (isNaN(chr3)) {
  6871. enc4 = 64;
  6872. }
  6873. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6874. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6875. }
  6876. return "data:image/png;base64," + output;
  6877. };
  6878. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6879. if (bias === void 0) { bias = null; }
  6880. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6881. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6882. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6883. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6884. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6885. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6886. }
  6887. if (bias) {
  6888. minimum.x -= minimum.x * bias.x + bias.y;
  6889. minimum.y -= minimum.y * bias.x + bias.y;
  6890. minimum.z -= minimum.z * bias.x + bias.y;
  6891. maximum.x += maximum.x * bias.x + bias.y;
  6892. maximum.y += maximum.y * bias.x + bias.y;
  6893. maximum.z += maximum.z * bias.x + bias.y;
  6894. }
  6895. return {
  6896. minimum: minimum,
  6897. maximum: maximum
  6898. };
  6899. };
  6900. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6901. if (bias === void 0) { bias = null; }
  6902. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6903. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6904. if (!stride) {
  6905. stride = 3;
  6906. }
  6907. for (var index = start; index < start + count; index++) {
  6908. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6909. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6910. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6911. }
  6912. if (bias) {
  6913. minimum.x -= minimum.x * bias.x + bias.y;
  6914. minimum.y -= minimum.y * bias.x + bias.y;
  6915. minimum.z -= minimum.z * bias.x + bias.y;
  6916. maximum.x += maximum.x * bias.x + bias.y;
  6917. maximum.y += maximum.y * bias.x + bias.y;
  6918. maximum.z += maximum.z * bias.x + bias.y;
  6919. }
  6920. return {
  6921. minimum: minimum,
  6922. maximum: maximum
  6923. };
  6924. };
  6925. Tools.Vector2ArrayFeeder = function (array) {
  6926. return function (index) {
  6927. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6928. var length = isFloatArray ? array.length / 2 : array.length;
  6929. if (index >= length) {
  6930. return null;
  6931. }
  6932. if (isFloatArray) {
  6933. var fa = array;
  6934. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6935. }
  6936. var a = array;
  6937. return a[index];
  6938. };
  6939. };
  6940. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6941. if (bias === void 0) { bias = null; }
  6942. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6943. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6944. var i = 0;
  6945. var cur = feeder(i++);
  6946. while (cur) {
  6947. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6948. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6949. cur = feeder(i++);
  6950. }
  6951. if (bias) {
  6952. minimum.x -= minimum.x * bias.x + bias.y;
  6953. minimum.y -= minimum.y * bias.x + bias.y;
  6954. maximum.x += maximum.x * bias.x + bias.y;
  6955. maximum.y += maximum.y * bias.x + bias.y;
  6956. }
  6957. return {
  6958. minimum: minimum,
  6959. maximum: maximum
  6960. };
  6961. };
  6962. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6963. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6964. return null;
  6965. return Array.isArray(obj) ? obj : [obj];
  6966. };
  6967. // Misc.
  6968. Tools.GetPointerPrefix = function () {
  6969. var eventPrefix = "pointer";
  6970. // Check if pointer events are supported
  6971. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6972. eventPrefix = "mouse";
  6973. }
  6974. return eventPrefix;
  6975. };
  6976. /**
  6977. * @param func - the function to be called
  6978. * @param requester - the object that will request the next frame. Falls back to window.
  6979. */
  6980. Tools.QueueNewFrame = function (func, requester) {
  6981. if (!Tools.IsWindowObjectExist()) {
  6982. return setTimeout(func, 16);
  6983. }
  6984. if (!requester) {
  6985. requester = window;
  6986. }
  6987. if (requester.requestAnimationFrame) {
  6988. return requester.requestAnimationFrame(func);
  6989. }
  6990. else if (requester.msRequestAnimationFrame) {
  6991. return requester.msRequestAnimationFrame(func);
  6992. }
  6993. else if (requester.webkitRequestAnimationFrame) {
  6994. return requester.webkitRequestAnimationFrame(func);
  6995. }
  6996. else if (requester.mozRequestAnimationFrame) {
  6997. return requester.mozRequestAnimationFrame(func);
  6998. }
  6999. else if (requester.oRequestAnimationFrame) {
  7000. return requester.oRequestAnimationFrame(func);
  7001. }
  7002. else {
  7003. return window.setTimeout(func, 16);
  7004. }
  7005. };
  7006. Tools.RequestFullscreen = function (element) {
  7007. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7008. if (!requestFunction)
  7009. return;
  7010. requestFunction.call(element);
  7011. };
  7012. Tools.ExitFullscreen = function () {
  7013. if (document.exitFullscreen) {
  7014. document.exitFullscreen();
  7015. }
  7016. else if (document.mozCancelFullScreen) {
  7017. document.mozCancelFullScreen();
  7018. }
  7019. else if (document.webkitCancelFullScreen) {
  7020. document.webkitCancelFullScreen();
  7021. }
  7022. else if (document.msCancelFullScreen) {
  7023. document.msCancelFullScreen();
  7024. }
  7025. };
  7026. Tools.SetCorsBehavior = function (url, element) {
  7027. if (url && url.indexOf("data:") === 0) {
  7028. return;
  7029. }
  7030. if (Tools.CorsBehavior) {
  7031. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7032. element.crossOrigin = Tools.CorsBehavior;
  7033. }
  7034. else {
  7035. var result = Tools.CorsBehavior(url);
  7036. if (result) {
  7037. element.crossOrigin = result;
  7038. }
  7039. }
  7040. }
  7041. };
  7042. // External files
  7043. Tools.CleanUrl = function (url) {
  7044. url = url.replace(/#/mg, "%23");
  7045. return url;
  7046. };
  7047. Tools.LoadImage = function (url, onLoad, onError, database) {
  7048. if (url instanceof ArrayBuffer) {
  7049. url = Tools.EncodeArrayBufferTobase64(url);
  7050. }
  7051. url = Tools.CleanUrl(url);
  7052. url = Tools.PreprocessUrl(url);
  7053. var img = new Image();
  7054. Tools.SetCorsBehavior(url, img);
  7055. img.onload = function () {
  7056. onLoad(img);
  7057. };
  7058. img.onerror = function (err) {
  7059. Tools.Error("Error while trying to load image: " + url);
  7060. if (onError) {
  7061. onError("Error while trying to load image: " + url, err);
  7062. }
  7063. };
  7064. var noIndexedDB = function () {
  7065. img.src = url;
  7066. };
  7067. var loadFromIndexedDB = function () {
  7068. if (database) {
  7069. database.loadImageFromDB(url, img);
  7070. }
  7071. };
  7072. //ANY database to do!
  7073. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7074. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7075. }
  7076. else {
  7077. if (url.indexOf("file:") !== -1) {
  7078. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7079. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7080. try {
  7081. var blobURL;
  7082. try {
  7083. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7084. }
  7085. catch (ex) {
  7086. // Chrome doesn't support oneTimeOnly parameter
  7087. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7088. }
  7089. img.src = blobURL;
  7090. }
  7091. catch (e) {
  7092. img.src = "";
  7093. }
  7094. return img;
  7095. }
  7096. }
  7097. noIndexedDB();
  7098. }
  7099. return img;
  7100. };
  7101. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7102. url = Tools.CleanUrl(url);
  7103. url = Tools.PreprocessUrl(url);
  7104. // If file and file input are set
  7105. if (url.indexOf("file:") !== -1) {
  7106. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7107. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7108. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7109. }
  7110. }
  7111. var loadUrl = Tools.BaseUrl + url;
  7112. var aborted = false;
  7113. var fileRequest = {
  7114. onCompleteObservable: new BABYLON.Observable(),
  7115. abort: function () { return aborted = true; },
  7116. };
  7117. var requestFile = function () {
  7118. var request = new XMLHttpRequest();
  7119. var retryHandle = null;
  7120. fileRequest.abort = function () {
  7121. aborted = true;
  7122. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7123. request.abort();
  7124. }
  7125. if (retryHandle !== null) {
  7126. clearTimeout(retryHandle);
  7127. retryHandle = null;
  7128. }
  7129. };
  7130. var retryLoop = function (retryIndex) {
  7131. request.open('GET', loadUrl, true);
  7132. if (useArrayBuffer) {
  7133. request.responseType = "arraybuffer";
  7134. }
  7135. if (onProgress) {
  7136. request.addEventListener("progress", onProgress);
  7137. }
  7138. var onLoadEnd = function () {
  7139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7140. };
  7141. request.addEventListener("loadend", onLoadEnd);
  7142. var onReadyStateChange = function () {
  7143. if (aborted) {
  7144. return;
  7145. }
  7146. // In case of undefined state in some browsers.
  7147. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7148. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7149. request.removeEventListener("readystatechange", onReadyStateChange);
  7150. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7151. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7152. return;
  7153. }
  7154. var retryStrategy = Tools.DefaultRetryStrategy;
  7155. if (retryStrategy) {
  7156. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7157. if (waitTime !== -1) {
  7158. // Prevent the request from completing for retry.
  7159. request.removeEventListener("loadend", onLoadEnd);
  7160. request = new XMLHttpRequest();
  7161. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7162. return;
  7163. }
  7164. }
  7165. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7166. if (onError) {
  7167. onError(request, e);
  7168. }
  7169. else {
  7170. throw e;
  7171. }
  7172. }
  7173. };
  7174. request.addEventListener("readystatechange", onReadyStateChange);
  7175. request.send();
  7176. };
  7177. retryLoop(0);
  7178. };
  7179. // Caching all files
  7180. if (database && database.enableSceneOffline) {
  7181. var noIndexedDB_1 = function () {
  7182. if (!aborted) {
  7183. requestFile();
  7184. }
  7185. };
  7186. var loadFromIndexedDB = function () {
  7187. // TODO: database needs to support aborting and should return a IFileRequest
  7188. if (aborted) {
  7189. return;
  7190. }
  7191. if (database) {
  7192. database.loadFileFromDB(url, function (data) {
  7193. if (!aborted) {
  7194. onSuccess(data);
  7195. }
  7196. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7197. }, onProgress ? function (event) {
  7198. if (!aborted) {
  7199. onProgress(event);
  7200. }
  7201. } : undefined, noIndexedDB_1, useArrayBuffer);
  7202. }
  7203. };
  7204. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7205. }
  7206. else {
  7207. requestFile();
  7208. }
  7209. return fileRequest;
  7210. };
  7211. /**
  7212. * Load a script (identified by an url). When the url returns, the
  7213. * content of this file is added into a new script element, attached to the DOM (body element)
  7214. */
  7215. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7216. var head = document.getElementsByTagName('head')[0];
  7217. var script = document.createElement('script');
  7218. script.type = 'text/javascript';
  7219. script.src = scriptUrl;
  7220. script.onload = function () {
  7221. if (onSuccess) {
  7222. onSuccess();
  7223. }
  7224. };
  7225. script.onerror = function (e) {
  7226. if (onError) {
  7227. onError("Unable to load script", e);
  7228. }
  7229. };
  7230. head.appendChild(script);
  7231. };
  7232. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7233. var reader = new FileReader();
  7234. var request = {
  7235. onCompleteObservable: new BABYLON.Observable(),
  7236. abort: function () { return reader.abort(); },
  7237. };
  7238. reader.onloadend = function (e) {
  7239. request.onCompleteObservable.notifyObservers(request);
  7240. };
  7241. reader.onload = function (e) {
  7242. //target doesn't have result from ts 1.3
  7243. callback(e.target['result']);
  7244. };
  7245. reader.onprogress = progressCallback;
  7246. reader.readAsDataURL(fileToLoad);
  7247. return request;
  7248. };
  7249. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7250. var reader = new FileReader();
  7251. var request = {
  7252. onCompleteObservable: new BABYLON.Observable(),
  7253. abort: function () { return reader.abort(); },
  7254. };
  7255. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7256. reader.onerror = function (e) {
  7257. Tools.Log("Error while reading file: " + fileToLoad.name);
  7258. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7259. };
  7260. reader.onload = function (e) {
  7261. //target doesn't have result from ts 1.3
  7262. callback(e.target['result']);
  7263. };
  7264. if (progressCallBack) {
  7265. reader.onprogress = progressCallBack;
  7266. }
  7267. if (!useArrayBuffer) {
  7268. // Asynchronous read
  7269. reader.readAsText(fileToLoad);
  7270. }
  7271. else {
  7272. reader.readAsArrayBuffer(fileToLoad);
  7273. }
  7274. return request;
  7275. };
  7276. //returns a downloadable url to a file content.
  7277. Tools.FileAsURL = function (content) {
  7278. var fileBlob = new Blob([content]);
  7279. var url = window.URL || window.webkitURL;
  7280. var link = url.createObjectURL(fileBlob);
  7281. return link;
  7282. };
  7283. // Misc.
  7284. Tools.Format = function (value, decimals) {
  7285. if (decimals === void 0) { decimals = 2; }
  7286. return value.toFixed(decimals);
  7287. };
  7288. Tools.CheckExtends = function (v, min, max) {
  7289. if (v.x < min.x)
  7290. min.x = v.x;
  7291. if (v.y < min.y)
  7292. min.y = v.y;
  7293. if (v.z < min.z)
  7294. min.z = v.z;
  7295. if (v.x > max.x)
  7296. max.x = v.x;
  7297. if (v.y > max.y)
  7298. max.y = v.y;
  7299. if (v.z > max.z)
  7300. max.z = v.z;
  7301. };
  7302. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7303. for (var prop in source) {
  7304. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7305. continue;
  7306. }
  7307. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7308. continue;
  7309. }
  7310. var sourceValue = source[prop];
  7311. var typeOfSourceValue = typeof sourceValue;
  7312. if (typeOfSourceValue === "function") {
  7313. continue;
  7314. }
  7315. if (typeOfSourceValue === "object") {
  7316. if (sourceValue instanceof Array) {
  7317. destination[prop] = [];
  7318. if (sourceValue.length > 0) {
  7319. if (typeof sourceValue[0] == "object") {
  7320. for (var index = 0; index < sourceValue.length; index++) {
  7321. var clonedValue = cloneValue(sourceValue[index], destination);
  7322. if (destination[prop].indexOf(clonedValue) === -1) {
  7323. destination[prop].push(clonedValue);
  7324. }
  7325. }
  7326. }
  7327. else {
  7328. destination[prop] = sourceValue.slice(0);
  7329. }
  7330. }
  7331. }
  7332. else {
  7333. destination[prop] = cloneValue(sourceValue, destination);
  7334. }
  7335. }
  7336. else {
  7337. destination[prop] = sourceValue;
  7338. }
  7339. }
  7340. };
  7341. Tools.IsEmpty = function (obj) {
  7342. for (var i in obj) {
  7343. if (obj.hasOwnProperty(i)) {
  7344. return false;
  7345. }
  7346. }
  7347. return true;
  7348. };
  7349. Tools.RegisterTopRootEvents = function (events) {
  7350. for (var index = 0; index < events.length; index++) {
  7351. var event = events[index];
  7352. window.addEventListener(event.name, event.handler, false);
  7353. try {
  7354. if (window.parent) {
  7355. window.parent.addEventListener(event.name, event.handler, false);
  7356. }
  7357. }
  7358. catch (e) {
  7359. // Silently fails...
  7360. }
  7361. }
  7362. };
  7363. Tools.UnregisterTopRootEvents = function (events) {
  7364. for (var index = 0; index < events.length; index++) {
  7365. var event = events[index];
  7366. window.removeEventListener(event.name, event.handler);
  7367. try {
  7368. if (window.parent) {
  7369. window.parent.removeEventListener(event.name, event.handler);
  7370. }
  7371. }
  7372. catch (e) {
  7373. // Silently fails...
  7374. }
  7375. }
  7376. };
  7377. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7378. if (mimeType === void 0) { mimeType = "image/png"; }
  7379. // Read the contents of the framebuffer
  7380. var numberOfChannelsByLine = width * 4;
  7381. var halfHeight = height / 2;
  7382. //Reading datas from WebGL
  7383. var data = engine.readPixels(0, 0, width, height);
  7384. //To flip image on Y axis.
  7385. for (var i = 0; i < halfHeight; i++) {
  7386. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7387. var currentCell = j + i * numberOfChannelsByLine;
  7388. var targetLine = height - i - 1;
  7389. var targetCell = j + targetLine * numberOfChannelsByLine;
  7390. var temp = data[currentCell];
  7391. data[currentCell] = data[targetCell];
  7392. data[targetCell] = temp;
  7393. }
  7394. }
  7395. // Create a 2D canvas to store the result
  7396. if (!screenshotCanvas) {
  7397. screenshotCanvas = document.createElement('canvas');
  7398. }
  7399. screenshotCanvas.width = width;
  7400. screenshotCanvas.height = height;
  7401. var context = screenshotCanvas.getContext('2d');
  7402. if (context) {
  7403. // Copy the pixels to a 2D canvas
  7404. var imageData = context.createImageData(width, height);
  7405. var castData = (imageData.data);
  7406. castData.set(data);
  7407. context.putImageData(imageData, 0, 0);
  7408. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7409. }
  7410. };
  7411. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7412. if (mimeType === void 0) { mimeType = "image/png"; }
  7413. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7414. if (successCallback) {
  7415. successCallback(base64Image);
  7416. }
  7417. else {
  7418. // We need HTMLCanvasElement.toBlob for HD screenshots
  7419. if (!screenshotCanvas.toBlob) {
  7420. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7421. screenshotCanvas.toBlob = function (callback, type, quality) {
  7422. var _this = this;
  7423. setTimeout(function () {
  7424. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7425. for (var i = 0; i < len; i++) {
  7426. arr[i] = binStr.charCodeAt(i);
  7427. }
  7428. callback(new Blob([arr], { type: type || 'image/png' }));
  7429. });
  7430. };
  7431. }
  7432. screenshotCanvas.toBlob(function (blob) {
  7433. var url = URL.createObjectURL(blob);
  7434. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7435. if (("download" in document.createElement("a"))) {
  7436. var a = window.document.createElement("a");
  7437. a.href = url;
  7438. if (fileName) {
  7439. a.setAttribute("download", fileName);
  7440. }
  7441. else {
  7442. var date = new Date();
  7443. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7444. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7445. }
  7446. window.document.body.appendChild(a);
  7447. a.addEventListener("click", function () {
  7448. if (a.parentElement) {
  7449. a.parentElement.removeChild(a);
  7450. }
  7451. });
  7452. a.click();
  7453. }
  7454. else {
  7455. var newWindow = window.open("");
  7456. if (!newWindow)
  7457. return;
  7458. var img = newWindow.document.createElement("img");
  7459. img.onload = function () {
  7460. // no longer need to read the blob so it's revoked
  7461. URL.revokeObjectURL(url);
  7462. };
  7463. img.src = url;
  7464. newWindow.document.body.appendChild(img);
  7465. }
  7466. });
  7467. }
  7468. };
  7469. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7470. if (mimeType === void 0) { mimeType = "image/png"; }
  7471. var width;
  7472. var height;
  7473. // If a precision value is specified
  7474. if (size.precision) {
  7475. width = Math.round(engine.getRenderWidth() * size.precision);
  7476. height = Math.round(width / engine.getAspectRatio(camera));
  7477. }
  7478. else if (size.width && size.height) {
  7479. width = size.width;
  7480. height = size.height;
  7481. }
  7482. else if (size.width && !size.height) {
  7483. width = size.width;
  7484. height = Math.round(width / engine.getAspectRatio(camera));
  7485. }
  7486. else if (size.height && !size.width) {
  7487. height = size.height;
  7488. width = Math.round(height * engine.getAspectRatio(camera));
  7489. }
  7490. else if (!isNaN(size)) {
  7491. height = size;
  7492. width = size;
  7493. }
  7494. else {
  7495. Tools.Error("Invalid 'size' parameter !");
  7496. return;
  7497. }
  7498. if (!screenshotCanvas) {
  7499. screenshotCanvas = document.createElement('canvas');
  7500. }
  7501. screenshotCanvas.width = width;
  7502. screenshotCanvas.height = height;
  7503. var renderContext = screenshotCanvas.getContext("2d");
  7504. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7505. var newWidth = width;
  7506. var newHeight = newWidth / ratio;
  7507. if (newHeight > height) {
  7508. newHeight = height;
  7509. newWidth = newHeight * ratio;
  7510. }
  7511. var offsetX = Math.max(0, width - newWidth) / 2;
  7512. var offsetY = Math.max(0, height - newHeight) / 2;
  7513. var renderingCanvas = engine.getRenderingCanvas();
  7514. if (renderContext && renderingCanvas) {
  7515. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7516. }
  7517. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7518. };
  7519. /**
  7520. * Generates an image screenshot from the specified camera.
  7521. *
  7522. * @param engine The engine to use for rendering
  7523. * @param camera The camera to use for rendering
  7524. * @param size This parameter can be set to a single number or to an object with the
  7525. * following (optional) properties: precision, width, height. If a single number is passed,
  7526. * it will be used for both width and height. If an object is passed, the screenshot size
  7527. * will be derived from the parameters. The precision property is a multiplier allowing
  7528. * rendering at a higher or lower resolution.
  7529. * @param successCallback The callback receives a single parameter which contains the
  7530. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7531. * src parameter of an <img> to display it.
  7532. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7533. * Check your browser for supported MIME types.
  7534. * @param samples Texture samples (default: 1)
  7535. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7536. * @param fileName A name for for the downloaded file.
  7537. * @constructor
  7538. */
  7539. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7540. if (mimeType === void 0) { mimeType = "image/png"; }
  7541. if (samples === void 0) { samples = 1; }
  7542. if (antialiasing === void 0) { antialiasing = false; }
  7543. var width;
  7544. var height;
  7545. //If a precision value is specified
  7546. if (size.precision) {
  7547. width = Math.round(engine.getRenderWidth() * size.precision);
  7548. height = Math.round(width / engine.getAspectRatio(camera));
  7549. size = { width: width, height: height };
  7550. }
  7551. else if (size.width && size.height) {
  7552. width = size.width;
  7553. height = size.height;
  7554. }
  7555. else if (size.width && !size.height) {
  7556. width = size.width;
  7557. height = Math.round(width / engine.getAspectRatio(camera));
  7558. size = { width: width, height: height };
  7559. }
  7560. else if (size.height && !size.width) {
  7561. height = size.height;
  7562. width = Math.round(height * engine.getAspectRatio(camera));
  7563. size = { width: width, height: height };
  7564. }
  7565. else if (!isNaN(size)) {
  7566. height = size;
  7567. width = size;
  7568. }
  7569. else {
  7570. Tools.Error("Invalid 'size' parameter !");
  7571. return;
  7572. }
  7573. var scene = camera.getScene();
  7574. var previousCamera = null;
  7575. if (scene.activeCamera !== camera) {
  7576. previousCamera = scene.activeCamera;
  7577. scene.activeCamera = camera;
  7578. }
  7579. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7580. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7581. texture.renderList = null;
  7582. texture.samples = samples;
  7583. if (antialiasing) {
  7584. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7585. }
  7586. texture.onAfterRenderObservable.add(function () {
  7587. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7588. });
  7589. scene.incrementRenderId();
  7590. scene.resetCachedMaterial();
  7591. texture.render(true);
  7592. texture.dispose();
  7593. if (previousCamera) {
  7594. scene.activeCamera = previousCamera;
  7595. }
  7596. camera.getProjectionMatrix(true); // Force cache refresh;
  7597. };
  7598. // XHR response validator for local file scenario
  7599. Tools.ValidateXHRData = function (xhr, dataType) {
  7600. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7601. if (dataType === void 0) { dataType = 7; }
  7602. try {
  7603. if (dataType & 1) {
  7604. if (xhr.responseText && xhr.responseText.length > 0) {
  7605. return true;
  7606. }
  7607. else if (dataType === 1) {
  7608. return false;
  7609. }
  7610. }
  7611. if (dataType & 2) {
  7612. // Check header width and height since there is no "TGA" magic number
  7613. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7614. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7615. return true;
  7616. }
  7617. else if (dataType === 2) {
  7618. return false;
  7619. }
  7620. }
  7621. if (dataType & 4) {
  7622. // Check for the "DDS" magic number
  7623. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7624. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7625. return true;
  7626. }
  7627. else {
  7628. return false;
  7629. }
  7630. }
  7631. }
  7632. catch (e) {
  7633. // Global protection
  7634. }
  7635. return false;
  7636. };
  7637. /**
  7638. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7639. * Be aware Math.random() could cause collisions, but:
  7640. * "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"
  7641. */
  7642. Tools.RandomId = function () {
  7643. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7644. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7645. return v.toString(16);
  7646. });
  7647. };
  7648. Object.defineProperty(Tools, "NoneLogLevel", {
  7649. get: function () {
  7650. return Tools._NoneLogLevel;
  7651. },
  7652. enumerable: true,
  7653. configurable: true
  7654. });
  7655. Object.defineProperty(Tools, "MessageLogLevel", {
  7656. get: function () {
  7657. return Tools._MessageLogLevel;
  7658. },
  7659. enumerable: true,
  7660. configurable: true
  7661. });
  7662. Object.defineProperty(Tools, "WarningLogLevel", {
  7663. get: function () {
  7664. return Tools._WarningLogLevel;
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. Object.defineProperty(Tools, "ErrorLogLevel", {
  7670. get: function () {
  7671. return Tools._ErrorLogLevel;
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Object.defineProperty(Tools, "AllLogLevel", {
  7677. get: function () {
  7678. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7679. },
  7680. enumerable: true,
  7681. configurable: true
  7682. });
  7683. Tools._AddLogEntry = function (entry) {
  7684. Tools._LogCache = entry + Tools._LogCache;
  7685. if (Tools.OnNewCacheEntry) {
  7686. Tools.OnNewCacheEntry(entry);
  7687. }
  7688. };
  7689. Tools._FormatMessage = function (message) {
  7690. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7691. var date = new Date();
  7692. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7693. };
  7694. Tools._LogDisabled = function (message) {
  7695. // nothing to do
  7696. };
  7697. Tools._LogEnabled = function (message) {
  7698. var formattedMessage = Tools._FormatMessage(message);
  7699. console.log("BJS - " + formattedMessage);
  7700. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7701. Tools._AddLogEntry(entry);
  7702. };
  7703. Tools._WarnDisabled = function (message) {
  7704. // nothing to do
  7705. };
  7706. Tools._WarnEnabled = function (message) {
  7707. var formattedMessage = Tools._FormatMessage(message);
  7708. console.warn("BJS - " + formattedMessage);
  7709. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7710. Tools._AddLogEntry(entry);
  7711. };
  7712. Tools._ErrorDisabled = function (message) {
  7713. // nothing to do
  7714. };
  7715. Tools._ErrorEnabled = function (message) {
  7716. Tools.errorsCount++;
  7717. var formattedMessage = Tools._FormatMessage(message);
  7718. console.error("BJS - " + formattedMessage);
  7719. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7720. Tools._AddLogEntry(entry);
  7721. };
  7722. Object.defineProperty(Tools, "LogCache", {
  7723. get: function () {
  7724. return Tools._LogCache;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Tools.ClearLogCache = function () {
  7730. Tools._LogCache = "";
  7731. Tools.errorsCount = 0;
  7732. };
  7733. Object.defineProperty(Tools, "LogLevels", {
  7734. set: function (level) {
  7735. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7736. Tools.Log = Tools._LogEnabled;
  7737. }
  7738. else {
  7739. Tools.Log = Tools._LogDisabled;
  7740. }
  7741. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7742. Tools.Warn = Tools._WarnEnabled;
  7743. }
  7744. else {
  7745. Tools.Warn = Tools._WarnDisabled;
  7746. }
  7747. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7748. Tools.Error = Tools._ErrorEnabled;
  7749. }
  7750. else {
  7751. Tools.Error = Tools._ErrorDisabled;
  7752. }
  7753. },
  7754. enumerable: true,
  7755. configurable: true
  7756. });
  7757. Tools.IsWindowObjectExist = function () {
  7758. return (typeof window) !== "undefined";
  7759. };
  7760. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7761. get: function () {
  7762. return Tools._PerformanceNoneLogLevel;
  7763. },
  7764. enumerable: true,
  7765. configurable: true
  7766. });
  7767. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7768. get: function () {
  7769. return Tools._PerformanceUserMarkLogLevel;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7775. get: function () {
  7776. return Tools._PerformanceConsoleLogLevel;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7782. set: function (level) {
  7783. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7784. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7785. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7786. return;
  7787. }
  7788. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7789. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7790. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7791. return;
  7792. }
  7793. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7794. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7795. },
  7796. enumerable: true,
  7797. configurable: true
  7798. });
  7799. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7800. };
  7801. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7802. };
  7803. Tools._StartUserMark = function (counterName, condition) {
  7804. if (condition === void 0) { condition = true; }
  7805. if (!Tools._performance) {
  7806. if (!Tools.IsWindowObjectExist()) {
  7807. return;
  7808. }
  7809. Tools._performance = window.performance;
  7810. }
  7811. if (!condition || !Tools._performance.mark) {
  7812. return;
  7813. }
  7814. Tools._performance.mark(counterName + "-Begin");
  7815. };
  7816. Tools._EndUserMark = function (counterName, condition) {
  7817. if (condition === void 0) { condition = true; }
  7818. if (!condition || !Tools._performance.mark) {
  7819. return;
  7820. }
  7821. Tools._performance.mark(counterName + "-End");
  7822. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7823. };
  7824. Tools._StartPerformanceConsole = function (counterName, condition) {
  7825. if (condition === void 0) { condition = true; }
  7826. if (!condition) {
  7827. return;
  7828. }
  7829. Tools._StartUserMark(counterName, condition);
  7830. if (console.time) {
  7831. console.time(counterName);
  7832. }
  7833. };
  7834. Tools._EndPerformanceConsole = function (counterName, condition) {
  7835. if (condition === void 0) { condition = true; }
  7836. if (!condition) {
  7837. return;
  7838. }
  7839. Tools._EndUserMark(counterName, condition);
  7840. if (console.time) {
  7841. console.timeEnd(counterName);
  7842. }
  7843. };
  7844. Object.defineProperty(Tools, "Now", {
  7845. get: function () {
  7846. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7847. return window.performance.now();
  7848. }
  7849. return new Date().getTime();
  7850. },
  7851. enumerable: true,
  7852. configurable: true
  7853. });
  7854. /**
  7855. * This method will return the name of the class used to create the instance of the given object.
  7856. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7857. * @param object the object to get the class name from
  7858. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7859. */
  7860. Tools.GetClassName = function (object, isType) {
  7861. if (isType === void 0) { isType = false; }
  7862. var name = null;
  7863. if (!isType && object.getClassName) {
  7864. name = object.getClassName();
  7865. }
  7866. else {
  7867. if (object instanceof Object) {
  7868. var classObj = isType ? object : Object.getPrototypeOf(object);
  7869. name = classObj.constructor["__bjsclassName__"];
  7870. }
  7871. if (!name) {
  7872. name = typeof object;
  7873. }
  7874. }
  7875. return name;
  7876. };
  7877. Tools.First = function (array, predicate) {
  7878. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7879. var el = array_1[_i];
  7880. if (predicate(el)) {
  7881. return el;
  7882. }
  7883. }
  7884. return null;
  7885. };
  7886. /**
  7887. * This method will return the name of the full name of the class, including its owning module (if any).
  7888. * 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).
  7889. * @param object the object to get the class name from
  7890. * @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.
  7891. */
  7892. Tools.getFullClassName = function (object, isType) {
  7893. if (isType === void 0) { isType = false; }
  7894. var className = null;
  7895. var moduleName = null;
  7896. if (!isType && object.getClassName) {
  7897. className = object.getClassName();
  7898. }
  7899. else {
  7900. if (object instanceof Object) {
  7901. var classObj = isType ? object : Object.getPrototypeOf(object);
  7902. className = classObj.constructor["__bjsclassName__"];
  7903. moduleName = classObj.constructor["__bjsmoduleName__"];
  7904. }
  7905. if (!className) {
  7906. className = typeof object;
  7907. }
  7908. }
  7909. if (!className) {
  7910. return null;
  7911. }
  7912. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7913. };
  7914. /**
  7915. * 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.
  7916. * @param array
  7917. */
  7918. Tools.arrayOrStringFeeder = function (array) {
  7919. return function (index) {
  7920. if (index >= array.length) {
  7921. return null;
  7922. }
  7923. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7924. if (val && val.getHashCode) {
  7925. val = val.getHashCode();
  7926. }
  7927. if (typeof val === "string") {
  7928. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7929. }
  7930. return val;
  7931. };
  7932. };
  7933. /**
  7934. * Compute the hashCode of a stream of number
  7935. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7936. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7937. * @return the hash code computed
  7938. */
  7939. Tools.hashCodeFromStream = function (feeder) {
  7940. // Based from here: http://stackoverflow.com/a/7616484/802124
  7941. var hash = 0;
  7942. var index = 0;
  7943. var chr = feeder(index++);
  7944. while (chr != null) {
  7945. hash = ((hash << 5) - hash) + chr;
  7946. hash |= 0; // Convert to 32bit integer
  7947. chr = feeder(index++);
  7948. }
  7949. return hash;
  7950. };
  7951. Tools.BaseUrl = "";
  7952. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7953. /**
  7954. * Default behaviour for cors in the application.
  7955. * It can be a string if the expected behavior is identical in the entire app.
  7956. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7957. */
  7958. Tools.CorsBehavior = "anonymous";
  7959. Tools.UseFallbackTexture = true;
  7960. /**
  7961. * Use this object to register external classes like custom textures or material
  7962. * to allow the laoders to instantiate them
  7963. */
  7964. Tools.RegisteredExternalClasses = {};
  7965. // Used in case of a texture loading problem
  7966. 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";
  7967. Tools.PreprocessUrl = function (url) {
  7968. return url;
  7969. };
  7970. // Logs
  7971. Tools._NoneLogLevel = 0;
  7972. Tools._MessageLogLevel = 1;
  7973. Tools._WarningLogLevel = 2;
  7974. Tools._ErrorLogLevel = 4;
  7975. Tools._LogCache = "";
  7976. Tools.errorsCount = 0;
  7977. Tools.Log = Tools._LogEnabled;
  7978. Tools.Warn = Tools._WarnEnabled;
  7979. Tools.Error = Tools._ErrorEnabled;
  7980. // Performances
  7981. Tools._PerformanceNoneLogLevel = 0;
  7982. Tools._PerformanceUserMarkLogLevel = 1;
  7983. Tools._PerformanceConsoleLogLevel = 2;
  7984. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7985. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7986. return Tools;
  7987. }());
  7988. BABYLON.Tools = Tools;
  7989. /**
  7990. * This class is used to track a performance counter which is number based.
  7991. * The user has access to many properties which give statistics of different nature
  7992. *
  7993. * The implementer can track two kinds of Performance Counter: time and count
  7994. * 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.
  7995. * 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.
  7996. */
  7997. var PerfCounter = /** @class */ (function () {
  7998. function PerfCounter() {
  7999. this._startMonitoringTime = 0;
  8000. this._min = 0;
  8001. this._max = 0;
  8002. this._average = 0;
  8003. this._lastSecAverage = 0;
  8004. this._current = 0;
  8005. this._totalValueCount = 0;
  8006. this._totalAccumulated = 0;
  8007. this._lastSecAccumulated = 0;
  8008. this._lastSecTime = 0;
  8009. this._lastSecValueCount = 0;
  8010. }
  8011. Object.defineProperty(PerfCounter.prototype, "min", {
  8012. /**
  8013. * Returns the smallest value ever
  8014. */
  8015. get: function () {
  8016. return this._min;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. Object.defineProperty(PerfCounter.prototype, "max", {
  8022. /**
  8023. * Returns the biggest value ever
  8024. */
  8025. get: function () {
  8026. return this._max;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(PerfCounter.prototype, "average", {
  8032. /**
  8033. * Returns the average value since the performance counter is running
  8034. */
  8035. get: function () {
  8036. return this._average;
  8037. },
  8038. enumerable: true,
  8039. configurable: true
  8040. });
  8041. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8042. /**
  8043. * Returns the average value of the last second the counter was monitored
  8044. */
  8045. get: function () {
  8046. return this._lastSecAverage;
  8047. },
  8048. enumerable: true,
  8049. configurable: true
  8050. });
  8051. Object.defineProperty(PerfCounter.prototype, "current", {
  8052. /**
  8053. * Returns the current value
  8054. */
  8055. get: function () {
  8056. return this._current;
  8057. },
  8058. enumerable: true,
  8059. configurable: true
  8060. });
  8061. Object.defineProperty(PerfCounter.prototype, "total", {
  8062. get: function () {
  8063. return this._totalAccumulated;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Object.defineProperty(PerfCounter.prototype, "count", {
  8069. get: function () {
  8070. return this._totalValueCount;
  8071. },
  8072. enumerable: true,
  8073. configurable: true
  8074. });
  8075. /**
  8076. * Call this method to start monitoring a new frame.
  8077. * 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.
  8078. */
  8079. PerfCounter.prototype.fetchNewFrame = function () {
  8080. this._totalValueCount++;
  8081. this._current = 0;
  8082. this._lastSecValueCount++;
  8083. };
  8084. /**
  8085. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8086. * @param newCount the count value to add to the monitored count
  8087. * @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.
  8088. */
  8089. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8090. if (!PerfCounter.Enabled) {
  8091. return;
  8092. }
  8093. this._current += newCount;
  8094. if (fetchResult) {
  8095. this._fetchResult();
  8096. }
  8097. };
  8098. /**
  8099. * Start monitoring this performance counter
  8100. */
  8101. PerfCounter.prototype.beginMonitoring = function () {
  8102. if (!PerfCounter.Enabled) {
  8103. return;
  8104. }
  8105. this._startMonitoringTime = Tools.Now;
  8106. };
  8107. /**
  8108. * Compute the time lapsed since the previous beginMonitoring() call.
  8109. * @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
  8110. */
  8111. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8112. if (newFrame === void 0) { newFrame = true; }
  8113. if (!PerfCounter.Enabled) {
  8114. return;
  8115. }
  8116. if (newFrame) {
  8117. this.fetchNewFrame();
  8118. }
  8119. var currentTime = Tools.Now;
  8120. this._current = currentTime - this._startMonitoringTime;
  8121. if (newFrame) {
  8122. this._fetchResult();
  8123. }
  8124. };
  8125. PerfCounter.prototype._fetchResult = function () {
  8126. this._totalAccumulated += this._current;
  8127. this._lastSecAccumulated += this._current;
  8128. // Min/Max update
  8129. this._min = Math.min(this._min, this._current);
  8130. this._max = Math.max(this._max, this._current);
  8131. this._average = this._totalAccumulated / this._totalValueCount;
  8132. // Reset last sec?
  8133. var now = Tools.Now;
  8134. if ((now - this._lastSecTime) > 1000) {
  8135. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8136. this._lastSecTime = now;
  8137. this._lastSecAccumulated = 0;
  8138. this._lastSecValueCount = 0;
  8139. }
  8140. };
  8141. PerfCounter.Enabled = true;
  8142. return PerfCounter;
  8143. }());
  8144. BABYLON.PerfCounter = PerfCounter;
  8145. /**
  8146. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8147. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8148. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8149. * @param name The name of the class, case should be preserved
  8150. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8151. */
  8152. function className(name, module) {
  8153. return function (target) {
  8154. target["__bjsclassName__"] = name;
  8155. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8156. };
  8157. }
  8158. BABYLON.className = className;
  8159. /**
  8160. * An implementation of a loop for asynchronous functions.
  8161. */
  8162. var AsyncLoop = /** @class */ (function () {
  8163. /**
  8164. * Constroctor.
  8165. * @param iterations the number of iterations.
  8166. * @param _fn the function to run each iteration
  8167. * @param _successCallback the callback that will be called upon succesful execution
  8168. * @param offset starting offset.
  8169. */
  8170. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8171. if (offset === void 0) { offset = 0; }
  8172. this.iterations = iterations;
  8173. this._fn = _fn;
  8174. this._successCallback = _successCallback;
  8175. this.index = offset - 1;
  8176. this._done = false;
  8177. }
  8178. /**
  8179. * Execute the next iteration. Must be called after the last iteration was finished.
  8180. */
  8181. AsyncLoop.prototype.executeNext = function () {
  8182. if (!this._done) {
  8183. if (this.index + 1 < this.iterations) {
  8184. ++this.index;
  8185. this._fn(this);
  8186. }
  8187. else {
  8188. this.breakLoop();
  8189. }
  8190. }
  8191. };
  8192. /**
  8193. * Break the loop and run the success callback.
  8194. */
  8195. AsyncLoop.prototype.breakLoop = function () {
  8196. this._done = true;
  8197. this._successCallback();
  8198. };
  8199. /**
  8200. * Helper function
  8201. */
  8202. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8203. if (offset === void 0) { offset = 0; }
  8204. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8205. loop.executeNext();
  8206. return loop;
  8207. };
  8208. /**
  8209. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8210. * @param iterations total number of iterations
  8211. * @param syncedIterations number of synchronous iterations in each async iteration.
  8212. * @param fn the function to call each iteration.
  8213. * @param callback a success call back that will be called when iterating stops.
  8214. * @param breakFunction a break condition (optional)
  8215. * @param timeout timeout settings for the setTimeout function. default - 0.
  8216. * @constructor
  8217. */
  8218. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8219. if (timeout === void 0) { timeout = 0; }
  8220. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8221. if (breakFunction && breakFunction())
  8222. loop.breakLoop();
  8223. else {
  8224. setTimeout(function () {
  8225. for (var i = 0; i < syncedIterations; ++i) {
  8226. var iteration = (loop.index * syncedIterations) + i;
  8227. if (iteration >= iterations)
  8228. break;
  8229. fn(iteration);
  8230. if (breakFunction && breakFunction()) {
  8231. loop.breakLoop();
  8232. break;
  8233. }
  8234. }
  8235. loop.executeNext();
  8236. }, timeout);
  8237. }
  8238. }, callback);
  8239. };
  8240. return AsyncLoop;
  8241. }());
  8242. BABYLON.AsyncLoop = AsyncLoop;
  8243. })(BABYLON || (BABYLON = {}));
  8244. //# sourceMappingURL=babylon.tools.js.map
  8245. var BABYLON;
  8246. (function (BABYLON) {
  8247. var PromiseStates;
  8248. (function (PromiseStates) {
  8249. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8250. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8251. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8252. })(PromiseStates || (PromiseStates = {}));
  8253. var FulFillmentAgregator = /** @class */ (function () {
  8254. function FulFillmentAgregator() {
  8255. this.count = 0;
  8256. this.target = 0;
  8257. this.results = [];
  8258. }
  8259. return FulFillmentAgregator;
  8260. }());
  8261. var InternalPromise = /** @class */ (function () {
  8262. function InternalPromise(resolver) {
  8263. var _this = this;
  8264. this._state = PromiseStates.Pending;
  8265. this._rejectWasConsumed = false;
  8266. if (!resolver) {
  8267. return;
  8268. }
  8269. try {
  8270. resolver(function (value) {
  8271. _this._resolve(value);
  8272. }, function (reason) {
  8273. _this._reject(reason);
  8274. });
  8275. }
  8276. catch (e) {
  8277. this._reject(e.message);
  8278. }
  8279. }
  8280. Object.defineProperty(InternalPromise.prototype, "state", {
  8281. get: function () {
  8282. return this._state;
  8283. },
  8284. enumerable: true,
  8285. configurable: true
  8286. });
  8287. InternalPromise.prototype.isFulfilled = function () {
  8288. return this._state === PromiseStates.Fulfilled;
  8289. };
  8290. InternalPromise.prototype.isRejected = function () {
  8291. return this._state === PromiseStates.Rejected;
  8292. };
  8293. InternalPromise.prototype.isPending = function () {
  8294. return this._state === PromiseStates.Pending;
  8295. };
  8296. InternalPromise.prototype.value = function () {
  8297. if (!this.isFulfilled()) {
  8298. throw new Error("Promise is not fulfilled");
  8299. }
  8300. return this._result;
  8301. };
  8302. InternalPromise.prototype.reason = function () {
  8303. if (!this.isRejected()) {
  8304. throw new Error("Promise is not rejected");
  8305. }
  8306. return this._reason;
  8307. };
  8308. InternalPromise.prototype.catch = function (onRejected) {
  8309. return this.then(undefined, onRejected);
  8310. };
  8311. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8312. var newPromise = new InternalPromise();
  8313. newPromise._onFulfilled = onFulfilled;
  8314. newPromise._onRejected = onRejected;
  8315. // Composition
  8316. this._child = newPromise;
  8317. if (this._state !== PromiseStates.Pending) {
  8318. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8319. var returnedPromise = newPromise._resolve(this._result);
  8320. if (returnedPromise) {
  8321. newPromise._child = returnedPromise;
  8322. newPromise = returnedPromise;
  8323. }
  8324. }
  8325. else {
  8326. newPromise._reject(this._reason);
  8327. }
  8328. }
  8329. return newPromise;
  8330. };
  8331. InternalPromise.prototype._resolve = function (value) {
  8332. try {
  8333. this._state = PromiseStates.Fulfilled;
  8334. this._result = value;
  8335. var returnedPromise = null;
  8336. if (this._onFulfilled) {
  8337. returnedPromise = this._onFulfilled(value);
  8338. }
  8339. if (this._child) {
  8340. this._child._resolve(value);
  8341. }
  8342. return returnedPromise;
  8343. }
  8344. catch (e) {
  8345. this._reject(e.message);
  8346. }
  8347. return null;
  8348. };
  8349. InternalPromise.prototype._reject = function (reason) {
  8350. this._state = PromiseStates.Rejected;
  8351. this._reason = reason;
  8352. if (this._onRejected) {
  8353. this._onRejected(reason);
  8354. this._rejectWasConsumed = true;
  8355. }
  8356. if (this._child) {
  8357. if (this._rejectWasConsumed) {
  8358. this._child._resolve(null);
  8359. }
  8360. else {
  8361. this._child._reject(reason);
  8362. }
  8363. }
  8364. };
  8365. InternalPromise.resolve = function (value) {
  8366. var newPromise = new InternalPromise();
  8367. newPromise._resolve(value);
  8368. return newPromise;
  8369. };
  8370. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8371. promise.then(function (value) {
  8372. agregator.results[index] = value;
  8373. agregator.count++;
  8374. if (agregator.count === agregator.target) {
  8375. agregator.rootPromise._resolve(agregator.results);
  8376. }
  8377. return null;
  8378. }, function (reason) {
  8379. if (!agregator.rootPromise.isRejected) {
  8380. agregator.rootPromise._reject(reason);
  8381. }
  8382. });
  8383. };
  8384. InternalPromise.all = function (promises) {
  8385. var newPromise = new InternalPromise();
  8386. var agregator = new FulFillmentAgregator();
  8387. agregator.target = promises.length;
  8388. agregator.rootPromise = newPromise;
  8389. for (var index = 0; index < promises.length; index++) {
  8390. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8391. }
  8392. return newPromise;
  8393. };
  8394. return InternalPromise;
  8395. }());
  8396. /**
  8397. * Helper class that provides a small promise polyfill
  8398. */
  8399. var PromisePolyfill = /** @class */ (function () {
  8400. function PromisePolyfill() {
  8401. }
  8402. /**
  8403. * Static function used to check if the polyfill is required
  8404. * If this is the case then the function will inject the polyfill to window.Promise
  8405. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8406. */
  8407. PromisePolyfill.Apply = function (force) {
  8408. if (force === void 0) { force = false; }
  8409. if (force || typeof Promise === 'undefined') {
  8410. var root = window;
  8411. root.Promise = InternalPromise;
  8412. }
  8413. };
  8414. return PromisePolyfill;
  8415. }());
  8416. BABYLON.PromisePolyfill = PromisePolyfill;
  8417. })(BABYLON || (BABYLON = {}));
  8418. //# sourceMappingURL=babylon.promise.js.map
  8419. var BABYLON;
  8420. (function (BABYLON) {
  8421. var _AlphaState = /** @class */ (function () {
  8422. /**
  8423. * Initializes the state.
  8424. */
  8425. function _AlphaState() {
  8426. this._isAlphaBlendDirty = false;
  8427. this._isBlendFunctionParametersDirty = false;
  8428. this._isBlendEquationParametersDirty = false;
  8429. this._isBlendConstantsDirty = false;
  8430. this._alphaBlend = false;
  8431. this._blendFunctionParameters = new Array(4);
  8432. this._blendEquationParameters = new Array(2);
  8433. this._blendConstants = new Array(4);
  8434. this.reset();
  8435. }
  8436. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8437. get: function () {
  8438. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8444. get: function () {
  8445. return this._alphaBlend;
  8446. },
  8447. set: function (value) {
  8448. if (this._alphaBlend === value) {
  8449. return;
  8450. }
  8451. this._alphaBlend = value;
  8452. this._isAlphaBlendDirty = true;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8458. if (this._blendConstants[0] === r &&
  8459. this._blendConstants[1] === g &&
  8460. this._blendConstants[2] === b &&
  8461. this._blendConstants[3] === a) {
  8462. return;
  8463. }
  8464. this._blendConstants[0] = r;
  8465. this._blendConstants[1] = g;
  8466. this._blendConstants[2] = b;
  8467. this._blendConstants[3] = a;
  8468. this._isBlendConstantsDirty = true;
  8469. };
  8470. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8471. if (this._blendFunctionParameters[0] === value0 &&
  8472. this._blendFunctionParameters[1] === value1 &&
  8473. this._blendFunctionParameters[2] === value2 &&
  8474. this._blendFunctionParameters[3] === value3) {
  8475. return;
  8476. }
  8477. this._blendFunctionParameters[0] = value0;
  8478. this._blendFunctionParameters[1] = value1;
  8479. this._blendFunctionParameters[2] = value2;
  8480. this._blendFunctionParameters[3] = value3;
  8481. this._isBlendFunctionParametersDirty = true;
  8482. };
  8483. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8484. if (this._blendEquationParameters[0] === rgb &&
  8485. this._blendEquationParameters[1] === alpha) {
  8486. return;
  8487. }
  8488. this._blendEquationParameters[0] = rgb;
  8489. this._blendEquationParameters[1] = alpha;
  8490. this._isBlendEquationParametersDirty = true;
  8491. };
  8492. _AlphaState.prototype.reset = function () {
  8493. this._alphaBlend = false;
  8494. this._blendFunctionParameters[0] = null;
  8495. this._blendFunctionParameters[1] = null;
  8496. this._blendFunctionParameters[2] = null;
  8497. this._blendFunctionParameters[3] = null;
  8498. this._blendEquationParameters[0] = null;
  8499. this._blendEquationParameters[1] = null;
  8500. this._blendConstants[0] = null;
  8501. this._blendConstants[1] = null;
  8502. this._blendConstants[2] = null;
  8503. this._blendConstants[3] = null;
  8504. this._isAlphaBlendDirty = true;
  8505. this._isBlendFunctionParametersDirty = false;
  8506. this._isBlendEquationParametersDirty = false;
  8507. this._isBlendConstantsDirty = false;
  8508. };
  8509. _AlphaState.prototype.apply = function (gl) {
  8510. if (!this.isDirty) {
  8511. return;
  8512. }
  8513. // Alpha blend
  8514. if (this._isAlphaBlendDirty) {
  8515. if (this._alphaBlend) {
  8516. gl.enable(gl.BLEND);
  8517. }
  8518. else {
  8519. gl.disable(gl.BLEND);
  8520. }
  8521. this._isAlphaBlendDirty = false;
  8522. }
  8523. // Alpha function
  8524. if (this._isBlendFunctionParametersDirty) {
  8525. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8526. this._isBlendFunctionParametersDirty = false;
  8527. }
  8528. // Alpha equation
  8529. if (this._isBlendEquationParametersDirty) {
  8530. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8531. this._isBlendEquationParametersDirty = false;
  8532. }
  8533. // Constants
  8534. if (this._isBlendConstantsDirty) {
  8535. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8536. this._isBlendConstantsDirty = false;
  8537. }
  8538. };
  8539. return _AlphaState;
  8540. }());
  8541. BABYLON._AlphaState = _AlphaState;
  8542. })(BABYLON || (BABYLON = {}));
  8543. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8544. var BABYLON;
  8545. (function (BABYLON) {
  8546. var _DepthCullingState = /** @class */ (function () {
  8547. /**
  8548. * Initializes the state.
  8549. */
  8550. function _DepthCullingState() {
  8551. this._isDepthTestDirty = false;
  8552. this._isDepthMaskDirty = false;
  8553. this._isDepthFuncDirty = false;
  8554. this._isCullFaceDirty = false;
  8555. this._isCullDirty = false;
  8556. this._isZOffsetDirty = false;
  8557. this._isFrontFaceDirty = false;
  8558. this.reset();
  8559. }
  8560. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8561. get: function () {
  8562. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8563. },
  8564. enumerable: true,
  8565. configurable: true
  8566. });
  8567. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8568. get: function () {
  8569. return this._zOffset;
  8570. },
  8571. set: function (value) {
  8572. if (this._zOffset === value) {
  8573. return;
  8574. }
  8575. this._zOffset = value;
  8576. this._isZOffsetDirty = true;
  8577. },
  8578. enumerable: true,
  8579. configurable: true
  8580. });
  8581. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8582. get: function () {
  8583. return this._cullFace;
  8584. },
  8585. set: function (value) {
  8586. if (this._cullFace === value) {
  8587. return;
  8588. }
  8589. this._cullFace = value;
  8590. this._isCullFaceDirty = true;
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8596. get: function () {
  8597. return this._cull;
  8598. },
  8599. set: function (value) {
  8600. if (this._cull === value) {
  8601. return;
  8602. }
  8603. this._cull = value;
  8604. this._isCullDirty = true;
  8605. },
  8606. enumerable: true,
  8607. configurable: true
  8608. });
  8609. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8610. get: function () {
  8611. return this._depthFunc;
  8612. },
  8613. set: function (value) {
  8614. if (this._depthFunc === value) {
  8615. return;
  8616. }
  8617. this._depthFunc = value;
  8618. this._isDepthFuncDirty = true;
  8619. },
  8620. enumerable: true,
  8621. configurable: true
  8622. });
  8623. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8624. get: function () {
  8625. return this._depthMask;
  8626. },
  8627. set: function (value) {
  8628. if (this._depthMask === value) {
  8629. return;
  8630. }
  8631. this._depthMask = value;
  8632. this._isDepthMaskDirty = true;
  8633. },
  8634. enumerable: true,
  8635. configurable: true
  8636. });
  8637. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8638. get: function () {
  8639. return this._depthTest;
  8640. },
  8641. set: function (value) {
  8642. if (this._depthTest === value) {
  8643. return;
  8644. }
  8645. this._depthTest = value;
  8646. this._isDepthTestDirty = true;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8652. get: function () {
  8653. return this._frontFace;
  8654. },
  8655. set: function (value) {
  8656. if (this._frontFace === value) {
  8657. return;
  8658. }
  8659. this._frontFace = value;
  8660. this._isFrontFaceDirty = true;
  8661. },
  8662. enumerable: true,
  8663. configurable: true
  8664. });
  8665. _DepthCullingState.prototype.reset = function () {
  8666. this._depthMask = true;
  8667. this._depthTest = true;
  8668. this._depthFunc = null;
  8669. this._cullFace = null;
  8670. this._cull = null;
  8671. this._zOffset = 0;
  8672. this._frontFace = null;
  8673. this._isDepthTestDirty = true;
  8674. this._isDepthMaskDirty = true;
  8675. this._isDepthFuncDirty = false;
  8676. this._isCullFaceDirty = false;
  8677. this._isCullDirty = false;
  8678. this._isZOffsetDirty = false;
  8679. this._isFrontFaceDirty = false;
  8680. };
  8681. _DepthCullingState.prototype.apply = function (gl) {
  8682. if (!this.isDirty) {
  8683. return;
  8684. }
  8685. // Cull
  8686. if (this._isCullDirty) {
  8687. if (this.cull) {
  8688. gl.enable(gl.CULL_FACE);
  8689. }
  8690. else {
  8691. gl.disable(gl.CULL_FACE);
  8692. }
  8693. this._isCullDirty = false;
  8694. }
  8695. // Cull face
  8696. if (this._isCullFaceDirty) {
  8697. gl.cullFace(this.cullFace);
  8698. this._isCullFaceDirty = false;
  8699. }
  8700. // Depth mask
  8701. if (this._isDepthMaskDirty) {
  8702. gl.depthMask(this.depthMask);
  8703. this._isDepthMaskDirty = false;
  8704. }
  8705. // Depth test
  8706. if (this._isDepthTestDirty) {
  8707. if (this.depthTest) {
  8708. gl.enable(gl.DEPTH_TEST);
  8709. }
  8710. else {
  8711. gl.disable(gl.DEPTH_TEST);
  8712. }
  8713. this._isDepthTestDirty = false;
  8714. }
  8715. // Depth func
  8716. if (this._isDepthFuncDirty) {
  8717. gl.depthFunc(this.depthFunc);
  8718. this._isDepthFuncDirty = false;
  8719. }
  8720. // zOffset
  8721. if (this._isZOffsetDirty) {
  8722. if (this.zOffset) {
  8723. gl.enable(gl.POLYGON_OFFSET_FILL);
  8724. gl.polygonOffset(this.zOffset, 0);
  8725. }
  8726. else {
  8727. gl.disable(gl.POLYGON_OFFSET_FILL);
  8728. }
  8729. this._isZOffsetDirty = false;
  8730. }
  8731. // Front face
  8732. if (this._isFrontFaceDirty) {
  8733. gl.frontFace(this.frontFace);
  8734. this._isFrontFaceDirty = false;
  8735. }
  8736. };
  8737. return _DepthCullingState;
  8738. }());
  8739. BABYLON._DepthCullingState = _DepthCullingState;
  8740. })(BABYLON || (BABYLON = {}));
  8741. //# sourceMappingURL=babylon.depthCullingState.js.map
  8742. var BABYLON;
  8743. (function (BABYLON) {
  8744. var _StencilState = /** @class */ (function () {
  8745. function _StencilState() {
  8746. this._isStencilTestDirty = false;
  8747. this._isStencilMaskDirty = false;
  8748. this._isStencilFuncDirty = false;
  8749. this._isStencilOpDirty = false;
  8750. this.reset();
  8751. }
  8752. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8753. get: function () {
  8754. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8755. },
  8756. enumerable: true,
  8757. configurable: true
  8758. });
  8759. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8760. get: function () {
  8761. return this._stencilFunc;
  8762. },
  8763. set: function (value) {
  8764. if (this._stencilFunc === value) {
  8765. return;
  8766. }
  8767. this._stencilFunc = value;
  8768. this._isStencilFuncDirty = true;
  8769. },
  8770. enumerable: true,
  8771. configurable: true
  8772. });
  8773. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8774. get: function () {
  8775. return this._stencilFuncRef;
  8776. },
  8777. set: function (value) {
  8778. if (this._stencilFuncRef === value) {
  8779. return;
  8780. }
  8781. this._stencilFuncRef = value;
  8782. this._isStencilFuncDirty = true;
  8783. },
  8784. enumerable: true,
  8785. configurable: true
  8786. });
  8787. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8788. get: function () {
  8789. return this._stencilFuncMask;
  8790. },
  8791. set: function (value) {
  8792. if (this._stencilFuncMask === value) {
  8793. return;
  8794. }
  8795. this._stencilFuncMask = value;
  8796. this._isStencilFuncDirty = true;
  8797. },
  8798. enumerable: true,
  8799. configurable: true
  8800. });
  8801. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8802. get: function () {
  8803. return this._stencilOpStencilFail;
  8804. },
  8805. set: function (value) {
  8806. if (this._stencilOpStencilFail === value) {
  8807. return;
  8808. }
  8809. this._stencilOpStencilFail = value;
  8810. this._isStencilOpDirty = true;
  8811. },
  8812. enumerable: true,
  8813. configurable: true
  8814. });
  8815. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8816. get: function () {
  8817. return this._stencilOpDepthFail;
  8818. },
  8819. set: function (value) {
  8820. if (this._stencilOpDepthFail === value) {
  8821. return;
  8822. }
  8823. this._stencilOpDepthFail = value;
  8824. this._isStencilOpDirty = true;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8830. get: function () {
  8831. return this._stencilOpStencilDepthPass;
  8832. },
  8833. set: function (value) {
  8834. if (this._stencilOpStencilDepthPass === value) {
  8835. return;
  8836. }
  8837. this._stencilOpStencilDepthPass = value;
  8838. this._isStencilOpDirty = true;
  8839. },
  8840. enumerable: true,
  8841. configurable: true
  8842. });
  8843. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8844. get: function () {
  8845. return this._stencilMask;
  8846. },
  8847. set: function (value) {
  8848. if (this._stencilMask === value) {
  8849. return;
  8850. }
  8851. this._stencilMask = value;
  8852. this._isStencilMaskDirty = true;
  8853. },
  8854. enumerable: true,
  8855. configurable: true
  8856. });
  8857. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8858. get: function () {
  8859. return this._stencilTest;
  8860. },
  8861. set: function (value) {
  8862. if (this._stencilTest === value) {
  8863. return;
  8864. }
  8865. this._stencilTest = value;
  8866. this._isStencilTestDirty = true;
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. _StencilState.prototype.reset = function () {
  8872. this._stencilTest = false;
  8873. this._stencilMask = 0xFF;
  8874. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8875. this._stencilFuncRef = 1;
  8876. this._stencilFuncMask = 0xFF;
  8877. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8878. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8879. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8880. this._isStencilTestDirty = true;
  8881. this._isStencilMaskDirty = true;
  8882. this._isStencilFuncDirty = true;
  8883. this._isStencilOpDirty = true;
  8884. };
  8885. _StencilState.prototype.apply = function (gl) {
  8886. if (!this.isDirty) {
  8887. return;
  8888. }
  8889. // Stencil test
  8890. if (this._isStencilTestDirty) {
  8891. if (this.stencilTest) {
  8892. gl.enable(gl.STENCIL_TEST);
  8893. }
  8894. else {
  8895. gl.disable(gl.STENCIL_TEST);
  8896. }
  8897. this._isStencilTestDirty = false;
  8898. }
  8899. // Stencil mask
  8900. if (this._isStencilMaskDirty) {
  8901. gl.stencilMask(this.stencilMask);
  8902. this._isStencilMaskDirty = false;
  8903. }
  8904. // Stencil func
  8905. if (this._isStencilFuncDirty) {
  8906. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8907. this._isStencilFuncDirty = false;
  8908. }
  8909. // Stencil op
  8910. if (this._isStencilOpDirty) {
  8911. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8912. this._isStencilOpDirty = false;
  8913. }
  8914. };
  8915. return _StencilState;
  8916. }());
  8917. BABYLON._StencilState = _StencilState;
  8918. })(BABYLON || (BABYLON = {}));
  8919. //# sourceMappingURL=babylon.stencilState.js.map
  8920. var BABYLON;
  8921. (function (BABYLON) {
  8922. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8923. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8924. };
  8925. var compileRawShader = function (gl, source, type) {
  8926. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8927. gl.shaderSource(shader, source);
  8928. gl.compileShader(shader);
  8929. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8930. var log = gl.getShaderInfoLog(shader);
  8931. if (log) {
  8932. throw new Error(log);
  8933. }
  8934. }
  8935. if (!shader) {
  8936. throw new Error("Something went wrong while compile the shader.");
  8937. }
  8938. return shader;
  8939. };
  8940. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8941. var magFilter = gl.NEAREST;
  8942. var minFilter = gl.NEAREST;
  8943. switch (samplingMode) {
  8944. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8945. magFilter = gl.LINEAR;
  8946. if (generateMipMaps) {
  8947. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8948. }
  8949. else {
  8950. minFilter = gl.LINEAR;
  8951. }
  8952. break;
  8953. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8954. magFilter = gl.LINEAR;
  8955. if (generateMipMaps) {
  8956. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8957. }
  8958. else {
  8959. minFilter = gl.LINEAR;
  8960. }
  8961. break;
  8962. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8963. magFilter = gl.NEAREST;
  8964. if (generateMipMaps) {
  8965. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8966. }
  8967. else {
  8968. minFilter = gl.NEAREST;
  8969. }
  8970. break;
  8971. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8972. magFilter = gl.NEAREST;
  8973. if (generateMipMaps) {
  8974. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8975. }
  8976. else {
  8977. minFilter = gl.NEAREST;
  8978. }
  8979. break;
  8980. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8981. magFilter = gl.NEAREST;
  8982. if (generateMipMaps) {
  8983. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8984. }
  8985. else {
  8986. minFilter = gl.LINEAR;
  8987. }
  8988. break;
  8989. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8990. magFilter = gl.NEAREST;
  8991. if (generateMipMaps) {
  8992. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8993. }
  8994. else {
  8995. minFilter = gl.LINEAR;
  8996. }
  8997. break;
  8998. case BABYLON.Texture.NEAREST_LINEAR:
  8999. magFilter = gl.NEAREST;
  9000. minFilter = gl.LINEAR;
  9001. break;
  9002. case BABYLON.Texture.NEAREST_NEAREST:
  9003. magFilter = gl.NEAREST;
  9004. minFilter = gl.NEAREST;
  9005. break;
  9006. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9007. magFilter = gl.LINEAR;
  9008. if (generateMipMaps) {
  9009. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9010. }
  9011. else {
  9012. minFilter = gl.NEAREST;
  9013. }
  9014. break;
  9015. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9016. magFilter = gl.LINEAR;
  9017. if (generateMipMaps) {
  9018. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9019. }
  9020. else {
  9021. minFilter = gl.NEAREST;
  9022. }
  9023. break;
  9024. case BABYLON.Texture.LINEAR_LINEAR:
  9025. magFilter = gl.LINEAR;
  9026. minFilter = gl.LINEAR;
  9027. break;
  9028. case BABYLON.Texture.LINEAR_NEAREST:
  9029. magFilter = gl.LINEAR;
  9030. minFilter = gl.NEAREST;
  9031. break;
  9032. }
  9033. return {
  9034. min: minFilter,
  9035. mag: magFilter
  9036. };
  9037. };
  9038. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9039. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9040. var img;
  9041. var onload = function () {
  9042. loadedImages[index] = img;
  9043. loadedImages._internalCount++;
  9044. if (scene) {
  9045. scene._removePendingData(img);
  9046. }
  9047. if (loadedImages._internalCount === 6) {
  9048. onfinish(loadedImages);
  9049. }
  9050. };
  9051. var onerror = function (message, exception) {
  9052. if (scene) {
  9053. scene._removePendingData(img);
  9054. }
  9055. if (onErrorCallBack) {
  9056. onErrorCallBack(message, exception);
  9057. }
  9058. };
  9059. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9060. if (scene) {
  9061. scene._addPendingData(img);
  9062. }
  9063. };
  9064. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9065. if (onError === void 0) { onError = null; }
  9066. var loadedImages = [];
  9067. loadedImages._internalCount = 0;
  9068. for (var index = 0; index < 6; index++) {
  9069. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9070. }
  9071. };
  9072. var BufferPointer = /** @class */ (function () {
  9073. function BufferPointer() {
  9074. }
  9075. return BufferPointer;
  9076. }());
  9077. var InstancingAttributeInfo = /** @class */ (function () {
  9078. function InstancingAttributeInfo() {
  9079. }
  9080. return InstancingAttributeInfo;
  9081. }());
  9082. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9083. /**
  9084. * Define options used to create a render target texture
  9085. */
  9086. var RenderTargetCreationOptions = /** @class */ (function () {
  9087. function RenderTargetCreationOptions() {
  9088. }
  9089. return RenderTargetCreationOptions;
  9090. }());
  9091. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9092. /**
  9093. * Regroup several parameters relative to the browser in use
  9094. */
  9095. var EngineCapabilities = /** @class */ (function () {
  9096. function EngineCapabilities() {
  9097. }
  9098. return EngineCapabilities;
  9099. }());
  9100. BABYLON.EngineCapabilities = EngineCapabilities;
  9101. /**
  9102. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9103. */
  9104. var Engine = /** @class */ (function () {
  9105. /**
  9106. * @constructor
  9107. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9108. * @param antialias defines enable antialiasing (default: false)
  9109. * @param options defines further options to be sent to the getContext() function
  9110. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9111. */
  9112. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9113. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9114. var _this = this;
  9115. // Public members
  9116. this.forcePOTTextures = false;
  9117. this.isFullscreen = false;
  9118. this.isPointerLock = false;
  9119. this.cullBackFaces = true;
  9120. this.renderEvenInBackground = true;
  9121. this.preventCacheWipeBetweenFrames = false;
  9122. // To enable/disable IDB support and avoid XHR on .manifest
  9123. this.enableOfflineSupport = false;
  9124. this.scenes = new Array();
  9125. this.postProcesses = new Array();
  9126. // Observables
  9127. /**
  9128. * Observable event triggered each time the rendering canvas is resized
  9129. */
  9130. this.onResizeObservable = new BABYLON.Observable();
  9131. /**
  9132. * Observable event triggered each time the canvas loses focus
  9133. */
  9134. this.onCanvasBlurObservable = new BABYLON.Observable();
  9135. /**
  9136. * Observable event triggered each time the canvas gains focus
  9137. */
  9138. this.onCanvasFocusObservable = new BABYLON.Observable();
  9139. /**
  9140. * Observable event triggered each time the canvas receives pointerout event
  9141. */
  9142. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9143. /**
  9144. * Observable event triggered before each texture is initialized
  9145. */
  9146. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9147. //WebVR
  9148. this._vrDisplay = undefined;
  9149. this._vrSupported = false;
  9150. this._vrExclusivePointerMode = false;
  9151. // Uniform buffers list
  9152. this.disableUniformBuffers = false;
  9153. this._uniformBuffers = new Array();
  9154. // Observables
  9155. /**
  9156. * Observable raised when the engine begins a new frame
  9157. */
  9158. this.onBeginFrameObservable = new BABYLON.Observable();
  9159. /**
  9160. * Observable raised when the engine ends the current frame
  9161. */
  9162. this.onEndFrameObservable = new BABYLON.Observable();
  9163. /**
  9164. * Observable raised when the engine is about to compile a shader
  9165. */
  9166. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9167. /**
  9168. * Observable raised when the engine has jsut compiled a shader
  9169. */
  9170. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9171. this._windowIsBackground = false;
  9172. this._webGLVersion = 1.0;
  9173. this._badOS = false;
  9174. this._badDesktopOS = false;
  9175. /**
  9176. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9177. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9178. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9179. */
  9180. this.disableTextureBindingOptimization = false;
  9181. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9182. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9183. this.onVRRequestPresentStart = new BABYLON.Observable();
  9184. this._colorWrite = true;
  9185. this._drawCalls = new BABYLON.PerfCounter();
  9186. this._textureCollisions = new BABYLON.PerfCounter();
  9187. this._renderingQueueLaunched = false;
  9188. this._activeRenderLoops = new Array();
  9189. // Deterministic lockstepMaxSteps
  9190. this._deterministicLockstep = false;
  9191. this._lockstepMaxSteps = 4;
  9192. // Lost context
  9193. this.onContextLostObservable = new BABYLON.Observable();
  9194. this.onContextRestoredObservable = new BABYLON.Observable();
  9195. this._contextWasLost = false;
  9196. this._doNotHandleContextLost = false;
  9197. // FPS
  9198. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9199. this._fps = 60;
  9200. this._deltaTime = 0;
  9201. /**
  9202. * Turn this value on if you want to pause FPS computation when in background
  9203. */
  9204. this.disablePerformanceMonitorInBackground = false;
  9205. // States
  9206. this._depthCullingState = new BABYLON._DepthCullingState();
  9207. this._stencilState = new BABYLON._StencilState();
  9208. this._alphaState = new BABYLON._AlphaState();
  9209. this._alphaMode = Engine.ALPHA_DISABLE;
  9210. // Cache
  9211. this._internalTexturesCache = new Array();
  9212. this._activeChannel = 0;
  9213. this._currentTextureChannel = -1;
  9214. this._boundTexturesCache = {};
  9215. this._compiledEffects = {};
  9216. this._vertexAttribArraysEnabled = [];
  9217. this._uintIndicesCurrentlySet = false;
  9218. this._currentBoundBuffer = new Array();
  9219. this._currentBufferPointers = new Array();
  9220. this._currentInstanceLocations = new Array();
  9221. this._currentInstanceBuffers = new Array();
  9222. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9223. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9224. this._vaoRecordInProgress = false;
  9225. this._mustWipeVertexAttributes = false;
  9226. this._nextFreeTextureSlots = new Array();
  9227. this._maxSimultaneousTextures = 0;
  9228. this._activeRequests = new Array();
  9229. // Hardware supported Compressed Textures
  9230. this._texturesSupported = new Array();
  9231. this._onVRFullScreenTriggered = function () {
  9232. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9233. //get the old size before we change
  9234. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9235. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9236. //get the width and height, change the render size
  9237. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9238. _this.setHardwareScalingLevel(1);
  9239. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9240. }
  9241. else {
  9242. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9243. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9244. }
  9245. };
  9246. this._boundUniforms = {};
  9247. // Register promises
  9248. BABYLON.PromisePolyfill.Apply();
  9249. var canvas = null;
  9250. Engine.Instances.push(this);
  9251. if (!canvasOrContext) {
  9252. return;
  9253. }
  9254. options = options || {};
  9255. if (canvasOrContext.getContext) {
  9256. canvas = canvasOrContext;
  9257. this._renderingCanvas = canvas;
  9258. if (antialias != null) {
  9259. options.antialias = antialias;
  9260. }
  9261. if (options.deterministicLockstep === undefined) {
  9262. options.deterministicLockstep = false;
  9263. }
  9264. if (options.lockstepMaxSteps === undefined) {
  9265. options.lockstepMaxSteps = 4;
  9266. }
  9267. if (options.preserveDrawingBuffer === undefined) {
  9268. options.preserveDrawingBuffer = false;
  9269. }
  9270. if (options.audioEngine === undefined) {
  9271. options.audioEngine = true;
  9272. }
  9273. if (options.stencil === undefined) {
  9274. options.stencil = true;
  9275. }
  9276. this._deterministicLockstep = options.deterministicLockstep;
  9277. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9278. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9279. // Exceptions
  9280. if (navigator && navigator.userAgent) {
  9281. var ua = navigator.userAgent;
  9282. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9283. var exception = _a[_i];
  9284. var key = exception.key;
  9285. var targets = exception.targets;
  9286. if (ua.indexOf(key) > -1) {
  9287. if (exception.capture && exception.captureConstraint) {
  9288. var capture = exception.capture;
  9289. var constraint = exception.captureConstraint;
  9290. var regex = new RegExp(capture);
  9291. var matches = regex.exec(ua);
  9292. if (matches && matches.length > 0) {
  9293. var capturedValue = parseInt(matches[matches.length - 1]);
  9294. if (capturedValue >= constraint) {
  9295. continue;
  9296. }
  9297. }
  9298. }
  9299. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9300. var target = targets_1[_b];
  9301. switch (target) {
  9302. case "uniformBuffer":
  9303. this.disableUniformBuffers = true;
  9304. break;
  9305. case "textureBindingOptimization":
  9306. this.disableTextureBindingOptimization = true;
  9307. break;
  9308. }
  9309. }
  9310. break;
  9311. }
  9312. }
  9313. }
  9314. // GL
  9315. if (!options.disableWebGL2Support) {
  9316. try {
  9317. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9318. if (this._gl) {
  9319. this._webGLVersion = 2.0;
  9320. }
  9321. }
  9322. catch (e) {
  9323. // Do nothing
  9324. }
  9325. }
  9326. if (!this._gl) {
  9327. if (!canvas) {
  9328. throw new Error("The provided canvas is null or undefined.");
  9329. }
  9330. try {
  9331. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9332. }
  9333. catch (e) {
  9334. throw new Error("WebGL not supported");
  9335. }
  9336. }
  9337. if (!this._gl) {
  9338. throw new Error("WebGL not supported");
  9339. }
  9340. this._onCanvasFocus = function () {
  9341. _this.onCanvasFocusObservable.notifyObservers(_this);
  9342. };
  9343. this._onCanvasBlur = function () {
  9344. _this.onCanvasBlurObservable.notifyObservers(_this);
  9345. };
  9346. canvas.addEventListener("focus", this._onCanvasFocus);
  9347. canvas.addEventListener("blur", this._onCanvasBlur);
  9348. this._onBlur = function () {
  9349. if (_this.disablePerformanceMonitorInBackground) {
  9350. _this._performanceMonitor.disable();
  9351. }
  9352. _this._windowIsBackground = true;
  9353. };
  9354. this._onFocus = function () {
  9355. if (_this.disablePerformanceMonitorInBackground) {
  9356. _this._performanceMonitor.enable();
  9357. }
  9358. _this._windowIsBackground = false;
  9359. };
  9360. this._onCanvasPointerOut = function () {
  9361. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9362. };
  9363. window.addEventListener("blur", this._onBlur);
  9364. window.addEventListener("focus", this._onFocus);
  9365. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9366. // Context lost
  9367. if (!this._doNotHandleContextLost) {
  9368. this._onContextLost = function (evt) {
  9369. evt.preventDefault();
  9370. _this._contextWasLost = true;
  9371. BABYLON.Tools.Warn("WebGL context lost.");
  9372. _this.onContextLostObservable.notifyObservers(_this);
  9373. };
  9374. this._onContextRestored = function (evt) {
  9375. // Adding a timeout to avoid race condition at browser level
  9376. setTimeout(function () {
  9377. // Rebuild gl context
  9378. _this._initGLContext();
  9379. // Rebuild effects
  9380. _this._rebuildEffects();
  9381. // Rebuild textures
  9382. _this._rebuildInternalTextures();
  9383. // Rebuild buffers
  9384. _this._rebuildBuffers();
  9385. // Cache
  9386. _this.wipeCaches(true);
  9387. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9388. _this.onContextRestoredObservable.notifyObservers(_this);
  9389. _this._contextWasLost = false;
  9390. }, 0);
  9391. };
  9392. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9393. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9394. }
  9395. }
  9396. else {
  9397. this._gl = canvasOrContext;
  9398. this._renderingCanvas = this._gl.canvas;
  9399. if (this._gl.renderbufferStorageMultisample) {
  9400. this._webGLVersion = 2.0;
  9401. }
  9402. options.stencil = this._gl.getContextAttributes().stencil;
  9403. }
  9404. // Viewport
  9405. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9406. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9407. this.resize();
  9408. this._isStencilEnable = options.stencil ? true : false;
  9409. this._initGLContext();
  9410. if (canvas) {
  9411. // Fullscreen
  9412. this._onFullscreenChange = function () {
  9413. if (document.fullscreen !== undefined) {
  9414. _this.isFullscreen = document.fullscreen;
  9415. }
  9416. else if (document.mozFullScreen !== undefined) {
  9417. _this.isFullscreen = document.mozFullScreen;
  9418. }
  9419. else if (document.webkitIsFullScreen !== undefined) {
  9420. _this.isFullscreen = document.webkitIsFullScreen;
  9421. }
  9422. else if (document.msIsFullScreen !== undefined) {
  9423. _this.isFullscreen = document.msIsFullScreen;
  9424. }
  9425. // Pointer lock
  9426. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9427. canvas.requestPointerLock = canvas.requestPointerLock ||
  9428. canvas.msRequestPointerLock ||
  9429. canvas.mozRequestPointerLock ||
  9430. canvas.webkitRequestPointerLock;
  9431. if (canvas.requestPointerLock) {
  9432. canvas.requestPointerLock();
  9433. }
  9434. }
  9435. };
  9436. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9437. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9438. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9439. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9440. // Pointer lock
  9441. this._onPointerLockChange = function () {
  9442. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9443. document.webkitPointerLockElement === canvas ||
  9444. document.msPointerLockElement === canvas ||
  9445. document.pointerLockElement === canvas);
  9446. };
  9447. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9448. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9449. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9450. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9451. this._onVRDisplayPointerRestricted = function () {
  9452. if (canvas) {
  9453. canvas.requestPointerLock();
  9454. }
  9455. };
  9456. this._onVRDisplayPointerUnrestricted = function () {
  9457. document.exitPointerLock();
  9458. };
  9459. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9460. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9461. }
  9462. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9463. Engine.audioEngine = new BABYLON.AudioEngine();
  9464. }
  9465. // Prepare buffer pointers
  9466. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9467. this._currentBufferPointers[i] = new BufferPointer();
  9468. }
  9469. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9470. // Load WebVR Devices
  9471. if (options.autoEnableWebVR) {
  9472. this.initWebVR();
  9473. }
  9474. // Detect if we are running on a faulty buggy OS.
  9475. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9476. // Detect if we are running on a faulty buggy desktop OS.
  9477. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9478. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9479. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9480. }
  9481. Object.defineProperty(Engine, "LastCreatedEngine", {
  9482. get: function () {
  9483. if (Engine.Instances.length === 0) {
  9484. return null;
  9485. }
  9486. return Engine.Instances[Engine.Instances.length - 1];
  9487. },
  9488. enumerable: true,
  9489. configurable: true
  9490. });
  9491. Object.defineProperty(Engine, "LastCreatedScene", {
  9492. get: function () {
  9493. var lastCreatedEngine = Engine.LastCreatedEngine;
  9494. if (!lastCreatedEngine) {
  9495. return null;
  9496. }
  9497. if (lastCreatedEngine.scenes.length === 0) {
  9498. return null;
  9499. }
  9500. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. /**
  9506. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9507. */
  9508. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9509. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9510. var engine = Engine.Instances[engineIndex];
  9511. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9512. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9513. }
  9514. }
  9515. };
  9516. Object.defineProperty(Engine, "NEVER", {
  9517. get: function () {
  9518. return Engine._NEVER;
  9519. },
  9520. enumerable: true,
  9521. configurable: true
  9522. });
  9523. Object.defineProperty(Engine, "ALWAYS", {
  9524. get: function () {
  9525. return Engine._ALWAYS;
  9526. },
  9527. enumerable: true,
  9528. configurable: true
  9529. });
  9530. Object.defineProperty(Engine, "LESS", {
  9531. get: function () {
  9532. return Engine._LESS;
  9533. },
  9534. enumerable: true,
  9535. configurable: true
  9536. });
  9537. Object.defineProperty(Engine, "EQUAL", {
  9538. get: function () {
  9539. return Engine._EQUAL;
  9540. },
  9541. enumerable: true,
  9542. configurable: true
  9543. });
  9544. Object.defineProperty(Engine, "LEQUAL", {
  9545. get: function () {
  9546. return Engine._LEQUAL;
  9547. },
  9548. enumerable: true,
  9549. configurable: true
  9550. });
  9551. Object.defineProperty(Engine, "GREATER", {
  9552. get: function () {
  9553. return Engine._GREATER;
  9554. },
  9555. enumerable: true,
  9556. configurable: true
  9557. });
  9558. Object.defineProperty(Engine, "GEQUAL", {
  9559. get: function () {
  9560. return Engine._GEQUAL;
  9561. },
  9562. enumerable: true,
  9563. configurable: true
  9564. });
  9565. Object.defineProperty(Engine, "NOTEQUAL", {
  9566. get: function () {
  9567. return Engine._NOTEQUAL;
  9568. },
  9569. enumerable: true,
  9570. configurable: true
  9571. });
  9572. Object.defineProperty(Engine, "KEEP", {
  9573. get: function () {
  9574. return Engine._KEEP;
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. Object.defineProperty(Engine, "REPLACE", {
  9580. get: function () {
  9581. return Engine._REPLACE;
  9582. },
  9583. enumerable: true,
  9584. configurable: true
  9585. });
  9586. Object.defineProperty(Engine, "INCR", {
  9587. get: function () {
  9588. return Engine._INCR;
  9589. },
  9590. enumerable: true,
  9591. configurable: true
  9592. });
  9593. Object.defineProperty(Engine, "DECR", {
  9594. get: function () {
  9595. return Engine._DECR;
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. Object.defineProperty(Engine, "INVERT", {
  9601. get: function () {
  9602. return Engine._INVERT;
  9603. },
  9604. enumerable: true,
  9605. configurable: true
  9606. });
  9607. Object.defineProperty(Engine, "INCR_WRAP", {
  9608. get: function () {
  9609. return Engine._INCR_WRAP;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(Engine, "DECR_WRAP", {
  9615. get: function () {
  9616. return Engine._DECR_WRAP;
  9617. },
  9618. enumerable: true,
  9619. configurable: true
  9620. });
  9621. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9622. get: function () {
  9623. return Engine._ALPHA_DISABLE;
  9624. },
  9625. enumerable: true,
  9626. configurable: true
  9627. });
  9628. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9629. get: function () {
  9630. return Engine._ALPHA_ONEONE;
  9631. },
  9632. enumerable: true,
  9633. configurable: true
  9634. });
  9635. Object.defineProperty(Engine, "ALPHA_ADD", {
  9636. get: function () {
  9637. return Engine._ALPHA_ADD;
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9643. get: function () {
  9644. return Engine._ALPHA_COMBINE;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9650. get: function () {
  9651. return Engine._ALPHA_SUBTRACT;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9657. get: function () {
  9658. return Engine._ALPHA_MULTIPLY;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9664. get: function () {
  9665. return Engine._ALPHA_MAXIMIZED;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9671. get: function () {
  9672. return Engine._ALPHA_PREMULTIPLIED;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9678. get: function () {
  9679. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9685. get: function () {
  9686. return Engine._ALPHA_INTERPOLATE;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9692. get: function () {
  9693. return Engine._ALPHA_SCREENMODE;
  9694. },
  9695. enumerable: true,
  9696. configurable: true
  9697. });
  9698. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9699. get: function () {
  9700. return Engine._DELAYLOADSTATE_NONE;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9706. get: function () {
  9707. return Engine._DELAYLOADSTATE_LOADED;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9713. get: function () {
  9714. return Engine._DELAYLOADSTATE_LOADING;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9720. get: function () {
  9721. return Engine._DELAYLOADSTATE_NOTLOADED;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9727. get: function () {
  9728. return Engine._TEXTUREFORMAT_ALPHA;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9734. get: function () {
  9735. return Engine._TEXTUREFORMAT_LUMINANCE;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9741. get: function () {
  9742. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9748. get: function () {
  9749. return Engine._TEXTUREFORMAT_RGB;
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9755. get: function () {
  9756. return Engine._TEXTUREFORMAT_RGBA;
  9757. },
  9758. enumerable: true,
  9759. configurable: true
  9760. });
  9761. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9762. get: function () {
  9763. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9764. },
  9765. enumerable: true,
  9766. configurable: true
  9767. });
  9768. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9769. get: function () {
  9770. return Engine._TEXTURETYPE_FLOAT;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9776. get: function () {
  9777. return Engine._TEXTURETYPE_HALF_FLOAT;
  9778. },
  9779. enumerable: true,
  9780. configurable: true
  9781. });
  9782. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9783. get: function () {
  9784. return Engine._SCALEMODE_FLOOR;
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9790. get: function () {
  9791. return Engine._SCALEMODE_NEAREST;
  9792. },
  9793. enumerable: true,
  9794. configurable: true
  9795. });
  9796. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9797. get: function () {
  9798. return Engine._SCALEMODE_CEILING;
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(Engine, "Version", {
  9804. get: function () {
  9805. return "3.2.0-alpha5";
  9806. },
  9807. enumerable: true,
  9808. configurable: true
  9809. });
  9810. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9811. get: function () {
  9812. return this._vrExclusivePointerMode;
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9818. get: function () {
  9819. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9820. },
  9821. enumerable: true,
  9822. configurable: true
  9823. });
  9824. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9825. get: function () {
  9826. return this._webGLVersion < 2 || this.forcePOTTextures;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(Engine.prototype, "badOS", {
  9832. get: function () {
  9833. return this._badOS;
  9834. },
  9835. enumerable: true,
  9836. configurable: true
  9837. });
  9838. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9839. get: function () {
  9840. return this._badDesktopOS;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9846. get: function () {
  9847. return this._performanceMonitor;
  9848. },
  9849. enumerable: true,
  9850. configurable: true
  9851. });
  9852. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9853. get: function () {
  9854. return this._texturesSupported;
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9860. get: function () {
  9861. return this._textureFormatInUse;
  9862. },
  9863. enumerable: true,
  9864. configurable: true
  9865. });
  9866. Object.defineProperty(Engine.prototype, "currentViewport", {
  9867. get: function () {
  9868. return this._cachedViewport;
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9874. // Empty texture
  9875. get: function () {
  9876. if (!this._emptyTexture) {
  9877. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9878. }
  9879. return this._emptyTexture;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9885. get: function () {
  9886. if (!this._emptyTexture3D) {
  9887. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9888. }
  9889. return this._emptyTexture3D;
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9895. get: function () {
  9896. if (!this._emptyCubeTexture) {
  9897. var faceData = new Uint8Array(4);
  9898. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9899. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9900. }
  9901. return this._emptyCubeTexture;
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Engine.prototype._rebuildInternalTextures = function () {
  9907. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9908. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9909. var internalTexture = currentState_1[_i];
  9910. internalTexture._rebuild();
  9911. }
  9912. };
  9913. Engine.prototype._rebuildEffects = function () {
  9914. for (var key in this._compiledEffects) {
  9915. var effect = this._compiledEffects[key];
  9916. effect._prepareEffect();
  9917. }
  9918. BABYLON.Effect.ResetCache();
  9919. };
  9920. Engine.prototype._rebuildBuffers = function () {
  9921. // Index / Vertex
  9922. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9923. var scene = _a[_i];
  9924. scene.resetCachedMaterial();
  9925. scene._rebuildGeometries();
  9926. scene._rebuildTextures();
  9927. }
  9928. // Uniforms
  9929. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9930. var uniformBuffer = _c[_b];
  9931. uniformBuffer._rebuild();
  9932. }
  9933. };
  9934. Engine.prototype._initGLContext = function () {
  9935. // Caps
  9936. this._caps = new EngineCapabilities();
  9937. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9938. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9939. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9940. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9941. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9942. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9943. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9944. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9945. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9946. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9947. // Infos
  9948. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9949. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9950. if (rendererInfo != null) {
  9951. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9952. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9953. }
  9954. if (!this._glVendor) {
  9955. this._glVendor = "Unknown vendor";
  9956. }
  9957. if (!this._glRenderer) {
  9958. this._glRenderer = "Unknown renderer";
  9959. }
  9960. // Constants
  9961. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9962. if (this._gl.RGBA16F !== 0x881A) {
  9963. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9964. }
  9965. if (this._gl.RGBA32F !== 0x8814) {
  9966. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9967. }
  9968. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9969. this._gl.DEPTH24_STENCIL8 = 35056;
  9970. }
  9971. // Extensions
  9972. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9973. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9974. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9975. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9976. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9977. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9978. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9979. 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');
  9980. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9981. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9982. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9983. this._caps.highPrecisionShaderSupported = true;
  9984. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9985. if (this._caps.timerQuery) {
  9986. if (this._webGLVersion === 1) {
  9987. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9988. }
  9989. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9990. }
  9991. // Checks if some of the format renders first to allow the use of webgl inspector.
  9992. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9993. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9994. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9995. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9996. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9997. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9998. if (this._webGLVersion > 1) {
  9999. this._gl.HALF_FLOAT_OES = 0x140B;
  10000. }
  10001. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10002. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10003. // Draw buffers
  10004. if (this._webGLVersion > 1) {
  10005. this._caps.drawBuffersExtension = true;
  10006. }
  10007. else {
  10008. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10009. if (drawBuffersExtension !== null) {
  10010. this._caps.drawBuffersExtension = true;
  10011. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10012. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10013. for (var i = 0; i < 16; i++) {
  10014. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10015. }
  10016. }
  10017. else {
  10018. this._caps.drawBuffersExtension = false;
  10019. }
  10020. }
  10021. // Depth Texture
  10022. if (this._webGLVersion > 1) {
  10023. this._caps.depthTextureExtension = true;
  10024. }
  10025. else {
  10026. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10027. if (depthTextureExtension != null) {
  10028. this._caps.depthTextureExtension = true;
  10029. }
  10030. }
  10031. // Vertex array object
  10032. if (this._webGLVersion > 1) {
  10033. this._caps.vertexArrayObject = true;
  10034. }
  10035. else {
  10036. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10037. if (vertexArrayObjectExtension != null) {
  10038. this._caps.vertexArrayObject = true;
  10039. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10040. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10041. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10042. }
  10043. else {
  10044. this._caps.vertexArrayObject = false;
  10045. }
  10046. }
  10047. // Instances count
  10048. if (this._webGLVersion > 1) {
  10049. this._caps.instancedArrays = true;
  10050. }
  10051. else {
  10052. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10053. if (instanceExtension != null) {
  10054. this._caps.instancedArrays = true;
  10055. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10056. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10057. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10058. }
  10059. else {
  10060. this._caps.instancedArrays = false;
  10061. }
  10062. }
  10063. // Intelligently add supported compressed formats in order to check for.
  10064. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10065. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10066. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10067. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10068. if (this._caps.astc)
  10069. this.texturesSupported.push('-astc.ktx');
  10070. if (this._caps.s3tc)
  10071. this.texturesSupported.push('-dxt.ktx');
  10072. if (this._caps.pvrtc)
  10073. this.texturesSupported.push('-pvrtc.ktx');
  10074. if (this._caps.etc2)
  10075. this.texturesSupported.push('-etc2.ktx');
  10076. if (this._caps.etc1)
  10077. this.texturesSupported.push('-etc1.ktx');
  10078. if (this._gl.getShaderPrecisionFormat) {
  10079. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10080. if (highp) {
  10081. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10082. }
  10083. }
  10084. // Depth buffer
  10085. this.setDepthBuffer(true);
  10086. this.setDepthFunctionToLessOrEqual();
  10087. this.setDepthWrite(true);
  10088. // Texture maps
  10089. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10090. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10091. this._nextFreeTextureSlots.push(slot);
  10092. }
  10093. };
  10094. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10095. get: function () {
  10096. return this._webGLVersion;
  10097. },
  10098. enumerable: true,
  10099. configurable: true
  10100. });
  10101. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10102. /**
  10103. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10104. */
  10105. get: function () {
  10106. return this._isStencilEnable;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Engine.prototype._prepareWorkingCanvas = function () {
  10112. if (this._workingCanvas) {
  10113. return;
  10114. }
  10115. this._workingCanvas = document.createElement("canvas");
  10116. var context = this._workingCanvas.getContext("2d");
  10117. if (context) {
  10118. this._workingContext = context;
  10119. }
  10120. };
  10121. Engine.prototype.resetTextureCache = function () {
  10122. for (var key in this._boundTexturesCache) {
  10123. var boundTexture = this._boundTexturesCache[key];
  10124. if (boundTexture) {
  10125. this._removeDesignatedSlot(boundTexture);
  10126. }
  10127. this._boundTexturesCache[key] = null;
  10128. }
  10129. this._nextFreeTextureSlots = [];
  10130. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10131. this._nextFreeTextureSlots.push(slot);
  10132. }
  10133. this._currentTextureChannel = -1;
  10134. };
  10135. Engine.prototype.isDeterministicLockStep = function () {
  10136. return this._deterministicLockstep;
  10137. };
  10138. Engine.prototype.getLockstepMaxSteps = function () {
  10139. return this._lockstepMaxSteps;
  10140. };
  10141. Engine.prototype.getGlInfo = function () {
  10142. return {
  10143. vendor: this._glVendor,
  10144. renderer: this._glRenderer,
  10145. version: this._glVersion
  10146. };
  10147. };
  10148. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10149. if (useScreen === void 0) { useScreen = false; }
  10150. var viewport = camera.viewport;
  10151. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10152. };
  10153. Engine.prototype.getRenderWidth = function (useScreen) {
  10154. if (useScreen === void 0) { useScreen = false; }
  10155. if (!useScreen && this._currentRenderTarget) {
  10156. return this._currentRenderTarget.width;
  10157. }
  10158. return this._gl.drawingBufferWidth;
  10159. };
  10160. Engine.prototype.getRenderHeight = function (useScreen) {
  10161. if (useScreen === void 0) { useScreen = false; }
  10162. if (!useScreen && this._currentRenderTarget) {
  10163. return this._currentRenderTarget.height;
  10164. }
  10165. return this._gl.drawingBufferHeight;
  10166. };
  10167. Engine.prototype.getRenderingCanvas = function () {
  10168. return this._renderingCanvas;
  10169. };
  10170. Engine.prototype.getRenderingCanvasClientRect = function () {
  10171. if (!this._renderingCanvas) {
  10172. return null;
  10173. }
  10174. return this._renderingCanvas.getBoundingClientRect();
  10175. };
  10176. Engine.prototype.setHardwareScalingLevel = function (level) {
  10177. this._hardwareScalingLevel = level;
  10178. this.resize();
  10179. };
  10180. Engine.prototype.getHardwareScalingLevel = function () {
  10181. return this._hardwareScalingLevel;
  10182. };
  10183. Engine.prototype.getLoadedTexturesCache = function () {
  10184. return this._internalTexturesCache;
  10185. };
  10186. Engine.prototype.getCaps = function () {
  10187. return this._caps;
  10188. };
  10189. Object.defineProperty(Engine.prototype, "drawCalls", {
  10190. /** The number of draw calls submitted last frame */
  10191. get: function () {
  10192. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10193. return 0;
  10194. },
  10195. enumerable: true,
  10196. configurable: true
  10197. });
  10198. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10199. get: function () {
  10200. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10201. return null;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. Engine.prototype.getDepthFunction = function () {
  10207. return this._depthCullingState.depthFunc;
  10208. };
  10209. Engine.prototype.setDepthFunction = function (depthFunc) {
  10210. this._depthCullingState.depthFunc = depthFunc;
  10211. };
  10212. Engine.prototype.setDepthFunctionToGreater = function () {
  10213. this._depthCullingState.depthFunc = this._gl.GREATER;
  10214. };
  10215. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10216. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10217. };
  10218. Engine.prototype.setDepthFunctionToLess = function () {
  10219. this._depthCullingState.depthFunc = this._gl.LESS;
  10220. };
  10221. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10222. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10223. };
  10224. Engine.prototype.getStencilBuffer = function () {
  10225. return this._stencilState.stencilTest;
  10226. };
  10227. Engine.prototype.setStencilBuffer = function (enable) {
  10228. this._stencilState.stencilTest = enable;
  10229. };
  10230. Engine.prototype.getStencilMask = function () {
  10231. return this._stencilState.stencilMask;
  10232. };
  10233. Engine.prototype.setStencilMask = function (mask) {
  10234. this._stencilState.stencilMask = mask;
  10235. };
  10236. Engine.prototype.getStencilFunction = function () {
  10237. return this._stencilState.stencilFunc;
  10238. };
  10239. Engine.prototype.getStencilFunctionReference = function () {
  10240. return this._stencilState.stencilFuncRef;
  10241. };
  10242. Engine.prototype.getStencilFunctionMask = function () {
  10243. return this._stencilState.stencilFuncMask;
  10244. };
  10245. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10246. this._stencilState.stencilFunc = stencilFunc;
  10247. };
  10248. Engine.prototype.setStencilFunctionReference = function (reference) {
  10249. this._stencilState.stencilFuncRef = reference;
  10250. };
  10251. Engine.prototype.setStencilFunctionMask = function (mask) {
  10252. this._stencilState.stencilFuncMask = mask;
  10253. };
  10254. Engine.prototype.getStencilOperationFail = function () {
  10255. return this._stencilState.stencilOpStencilFail;
  10256. };
  10257. Engine.prototype.getStencilOperationDepthFail = function () {
  10258. return this._stencilState.stencilOpDepthFail;
  10259. };
  10260. Engine.prototype.getStencilOperationPass = function () {
  10261. return this._stencilState.stencilOpStencilDepthPass;
  10262. };
  10263. Engine.prototype.setStencilOperationFail = function (operation) {
  10264. this._stencilState.stencilOpStencilFail = operation;
  10265. };
  10266. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10267. this._stencilState.stencilOpDepthFail = operation;
  10268. };
  10269. Engine.prototype.setStencilOperationPass = function (operation) {
  10270. this._stencilState.stencilOpStencilDepthPass = operation;
  10271. };
  10272. Engine.prototype.setDitheringState = function (value) {
  10273. if (value) {
  10274. this._gl.enable(this._gl.DITHER);
  10275. }
  10276. else {
  10277. this._gl.disable(this._gl.DITHER);
  10278. }
  10279. };
  10280. Engine.prototype.setRasterizerState = function (value) {
  10281. if (value) {
  10282. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10283. }
  10284. else {
  10285. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10286. }
  10287. };
  10288. /**
  10289. * stop executing a render loop function and remove it from the execution array
  10290. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10291. */
  10292. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10293. if (!renderFunction) {
  10294. this._activeRenderLoops = [];
  10295. return;
  10296. }
  10297. var index = this._activeRenderLoops.indexOf(renderFunction);
  10298. if (index >= 0) {
  10299. this._activeRenderLoops.splice(index, 1);
  10300. }
  10301. };
  10302. Engine.prototype._renderLoop = function () {
  10303. if (!this._contextWasLost) {
  10304. var shouldRender = true;
  10305. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10306. shouldRender = false;
  10307. }
  10308. if (shouldRender) {
  10309. // Start new frame
  10310. this.beginFrame();
  10311. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10312. var renderFunction = this._activeRenderLoops[index];
  10313. renderFunction();
  10314. }
  10315. // Present
  10316. this.endFrame();
  10317. }
  10318. }
  10319. if (this._activeRenderLoops.length > 0) {
  10320. // Register new frame
  10321. var requester = null;
  10322. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10323. requester = this._vrDisplay;
  10324. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10325. }
  10326. else {
  10327. this._renderingQueueLaunched = false;
  10328. }
  10329. };
  10330. /**
  10331. * Register and execute a render loop. The engine can have more than one render function.
  10332. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10333. * @example
  10334. * engine.runRenderLoop(function () {
  10335. * scene.render()
  10336. * })
  10337. */
  10338. Engine.prototype.runRenderLoop = function (renderFunction) {
  10339. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10340. return;
  10341. }
  10342. this._activeRenderLoops.push(renderFunction);
  10343. if (!this._renderingQueueLaunched) {
  10344. this._renderingQueueLaunched = true;
  10345. this._bindedRenderFunction = this._renderLoop.bind(this);
  10346. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10347. }
  10348. };
  10349. /**
  10350. * Toggle full screen mode.
  10351. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10352. * @param {any} options - an options object to be sent to the requestFullscreen function
  10353. */
  10354. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10355. if (this.isFullscreen) {
  10356. BABYLON.Tools.ExitFullscreen();
  10357. }
  10358. else {
  10359. this._pointerLockRequested = requestPointerLock;
  10360. if (this._renderingCanvas) {
  10361. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10362. }
  10363. }
  10364. };
  10365. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10366. if (stencil === void 0) { stencil = false; }
  10367. this.applyStates();
  10368. var mode = 0;
  10369. if (backBuffer && color) {
  10370. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10371. mode |= this._gl.COLOR_BUFFER_BIT;
  10372. }
  10373. if (depth) {
  10374. this._gl.clearDepth(1.0);
  10375. mode |= this._gl.DEPTH_BUFFER_BIT;
  10376. }
  10377. if (stencil) {
  10378. this._gl.clearStencil(0);
  10379. mode |= this._gl.STENCIL_BUFFER_BIT;
  10380. }
  10381. this._gl.clear(mode);
  10382. };
  10383. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10384. var gl = this._gl;
  10385. // Save state
  10386. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10387. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10388. // Change state
  10389. gl.enable(gl.SCISSOR_TEST);
  10390. gl.scissor(x, y, width, height);
  10391. // Clear
  10392. this.clear(clearColor, true, true, true);
  10393. // Restore state
  10394. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10395. if (curScissor === true) {
  10396. gl.enable(gl.SCISSOR_TEST);
  10397. }
  10398. else {
  10399. gl.disable(gl.SCISSOR_TEST);
  10400. }
  10401. };
  10402. /**
  10403. * Set the WebGL's viewport
  10404. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10405. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10406. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10407. */
  10408. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10409. var width = requiredWidth || this.getRenderWidth();
  10410. var height = requiredHeight || this.getRenderHeight();
  10411. var x = viewport.x || 0;
  10412. var y = viewport.y || 0;
  10413. this._cachedViewport = viewport;
  10414. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10415. };
  10416. /**
  10417. * Directly set the WebGL Viewport
  10418. * The x, y, width & height are directly passed to the WebGL call
  10419. * @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.
  10420. */
  10421. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10422. var currentViewport = this._cachedViewport;
  10423. this._cachedViewport = null;
  10424. this._gl.viewport(x, y, width, height);
  10425. return currentViewport;
  10426. };
  10427. Engine.prototype.beginFrame = function () {
  10428. this.onBeginFrameObservable.notifyObservers(this);
  10429. this._measureFps();
  10430. };
  10431. Engine.prototype.endFrame = function () {
  10432. //force a flush in case we are using a bad OS.
  10433. if (this._badOS) {
  10434. this.flushFramebuffer();
  10435. }
  10436. //submit frame to the vr device, if enabled
  10437. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10438. // TODO: We should only submit the frame if we read frameData successfully.
  10439. this._vrDisplay.submitFrame();
  10440. }
  10441. this.onEndFrameObservable.notifyObservers(this);
  10442. };
  10443. /**
  10444. * resize the view according to the canvas' size.
  10445. * @example
  10446. * window.addEventListener("resize", function () {
  10447. * engine.resize();
  10448. * });
  10449. */
  10450. Engine.prototype.resize = function () {
  10451. // We're not resizing the size of the canvas while in VR mode & presenting
  10452. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10453. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10454. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10455. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10456. }
  10457. };
  10458. /**
  10459. * force a specific size of the canvas
  10460. * @param {number} width - the new canvas' width
  10461. * @param {number} height - the new canvas' height
  10462. */
  10463. Engine.prototype.setSize = function (width, height) {
  10464. if (!this._renderingCanvas) {
  10465. return;
  10466. }
  10467. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10468. return;
  10469. }
  10470. this._renderingCanvas.width = width;
  10471. this._renderingCanvas.height = height;
  10472. for (var index = 0; index < this.scenes.length; index++) {
  10473. var scene = this.scenes[index];
  10474. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10475. var cam = scene.cameras[camIndex];
  10476. cam._currentRenderId = 0;
  10477. }
  10478. }
  10479. if (this.onResizeObservable.hasObservers) {
  10480. this.onResizeObservable.notifyObservers(this);
  10481. }
  10482. };
  10483. // WebVR functions
  10484. Engine.prototype.isVRDevicePresent = function () {
  10485. return !!this._vrDisplay;
  10486. };
  10487. Engine.prototype.getVRDevice = function () {
  10488. return this._vrDisplay;
  10489. };
  10490. Engine.prototype.initWebVR = function () {
  10491. var _this = this;
  10492. var notifyObservers = function () {
  10493. var eventArgs = {
  10494. vrDisplay: _this._vrDisplay,
  10495. vrSupported: _this._vrSupported
  10496. };
  10497. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10498. };
  10499. if (!this._onVrDisplayConnect) {
  10500. this._onVrDisplayConnect = function (event) {
  10501. _this._vrDisplay = event.display;
  10502. notifyObservers();
  10503. };
  10504. this._onVrDisplayDisconnect = function () {
  10505. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10506. _this._vrDisplay = undefined;
  10507. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10508. notifyObservers();
  10509. };
  10510. this._onVrDisplayPresentChange = function () {
  10511. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10512. };
  10513. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10514. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10515. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10516. }
  10517. this._getVRDisplays(notifyObservers);
  10518. return this.onVRDisplayChangedObservable;
  10519. };
  10520. Engine.prototype.enableVR = function () {
  10521. var _this = this;
  10522. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10523. var onResolved = function () {
  10524. _this.onVRRequestPresentComplete.notifyObservers(true);
  10525. _this._onVRFullScreenTriggered();
  10526. };
  10527. var onRejected = function () {
  10528. _this.onVRRequestPresentComplete.notifyObservers(false);
  10529. };
  10530. this.onVRRequestPresentStart.notifyObservers(this);
  10531. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10532. }
  10533. };
  10534. Engine.prototype.disableVR = function () {
  10535. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10536. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10537. }
  10538. };
  10539. Engine.prototype._getVRDisplays = function (callback) {
  10540. var _this = this;
  10541. var getWebVRDevices = function (devices) {
  10542. _this._vrSupported = true;
  10543. // note that devices may actually be an empty array. This is fine;
  10544. // we expect this._vrDisplay to be undefined in this case.
  10545. return _this._vrDisplay = devices[0];
  10546. };
  10547. if (navigator.getVRDisplays) {
  10548. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10549. // TODO: System CANNOT support WebVR, despite API presence.
  10550. _this._vrSupported = false;
  10551. callback();
  10552. });
  10553. }
  10554. else {
  10555. // TODO: Browser does not support WebVR
  10556. this._vrDisplay = undefined;
  10557. this._vrSupported = false;
  10558. callback();
  10559. }
  10560. };
  10561. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10562. if (this._currentRenderTarget) {
  10563. this.unBindFramebuffer(this._currentRenderTarget);
  10564. }
  10565. this._currentRenderTarget = texture;
  10566. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10567. var gl = this._gl;
  10568. if (texture.isCube) {
  10569. if (faceIndex === undefined) {
  10570. faceIndex = 0;
  10571. }
  10572. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10573. }
  10574. if (this._cachedViewport && !forceFullscreenViewport) {
  10575. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10576. }
  10577. else {
  10578. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10579. }
  10580. this.wipeCaches();
  10581. };
  10582. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10583. if (this._currentFramebuffer !== framebuffer) {
  10584. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10585. this._currentFramebuffer = framebuffer;
  10586. }
  10587. };
  10588. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10589. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10590. this._currentRenderTarget = null;
  10591. // If MSAA, we need to bitblt back to main texture
  10592. var gl = this._gl;
  10593. if (texture._MSAAFramebuffer) {
  10594. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10595. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10596. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10597. }
  10598. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10599. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10600. gl.generateMipmap(gl.TEXTURE_2D);
  10601. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10602. }
  10603. if (onBeforeUnbind) {
  10604. if (texture._MSAAFramebuffer) {
  10605. // Bind the correct framebuffer
  10606. this.bindUnboundFramebuffer(texture._framebuffer);
  10607. }
  10608. onBeforeUnbind();
  10609. }
  10610. this.bindUnboundFramebuffer(null);
  10611. };
  10612. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10613. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10614. this._currentRenderTarget = null;
  10615. // If MSAA, we need to bitblt back to main texture
  10616. var gl = this._gl;
  10617. if (textures[0]._MSAAFramebuffer) {
  10618. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10619. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10620. var attachments = textures[0]._attachments;
  10621. if (!attachments) {
  10622. attachments = new Array(textures.length);
  10623. textures[0]._attachments = attachments;
  10624. }
  10625. for (var i = 0; i < textures.length; i++) {
  10626. var texture = textures[i];
  10627. for (var j = 0; j < attachments.length; j++) {
  10628. attachments[j] = gl.NONE;
  10629. }
  10630. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10631. gl.readBuffer(attachments[i]);
  10632. gl.drawBuffers(attachments);
  10633. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10634. }
  10635. for (var i = 0; i < attachments.length; i++) {
  10636. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10637. }
  10638. gl.drawBuffers(attachments);
  10639. }
  10640. for (var i = 0; i < textures.length; i++) {
  10641. var texture = textures[i];
  10642. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10643. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10644. gl.generateMipmap(gl.TEXTURE_2D);
  10645. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10646. }
  10647. }
  10648. if (onBeforeUnbind) {
  10649. if (textures[0]._MSAAFramebuffer) {
  10650. // Bind the correct framebuffer
  10651. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10652. }
  10653. onBeforeUnbind();
  10654. }
  10655. this.bindUnboundFramebuffer(null);
  10656. };
  10657. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10658. if (texture.generateMipMaps) {
  10659. var gl = this._gl;
  10660. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10661. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10662. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10663. }
  10664. };
  10665. Engine.prototype.flushFramebuffer = function () {
  10666. this._gl.flush();
  10667. };
  10668. Engine.prototype.restoreDefaultFramebuffer = function () {
  10669. if (this._currentRenderTarget) {
  10670. this.unBindFramebuffer(this._currentRenderTarget);
  10671. }
  10672. else {
  10673. this.bindUnboundFramebuffer(null);
  10674. }
  10675. if (this._cachedViewport) {
  10676. this.setViewport(this._cachedViewport);
  10677. }
  10678. this.wipeCaches();
  10679. };
  10680. // UBOs
  10681. Engine.prototype.createUniformBuffer = function (elements) {
  10682. var ubo = this._gl.createBuffer();
  10683. if (!ubo) {
  10684. throw new Error("Unable to create uniform buffer");
  10685. }
  10686. this.bindUniformBuffer(ubo);
  10687. if (elements instanceof Float32Array) {
  10688. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10689. }
  10690. else {
  10691. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10692. }
  10693. this.bindUniformBuffer(null);
  10694. ubo.references = 1;
  10695. return ubo;
  10696. };
  10697. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10698. var ubo = this._gl.createBuffer();
  10699. if (!ubo) {
  10700. throw new Error("Unable to create dynamic uniform buffer");
  10701. }
  10702. this.bindUniformBuffer(ubo);
  10703. if (elements instanceof Float32Array) {
  10704. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10705. }
  10706. else {
  10707. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10708. }
  10709. this.bindUniformBuffer(null);
  10710. ubo.references = 1;
  10711. return ubo;
  10712. };
  10713. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10714. this.bindUniformBuffer(uniformBuffer);
  10715. if (offset === undefined) {
  10716. offset = 0;
  10717. }
  10718. if (count === undefined) {
  10719. if (elements instanceof Float32Array) {
  10720. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10721. }
  10722. else {
  10723. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10724. }
  10725. }
  10726. else {
  10727. if (elements instanceof Float32Array) {
  10728. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10729. }
  10730. else {
  10731. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10732. }
  10733. }
  10734. this.bindUniformBuffer(null);
  10735. };
  10736. // VBOs
  10737. Engine.prototype._resetVertexBufferBinding = function () {
  10738. this.bindArrayBuffer(null);
  10739. this._cachedVertexBuffers = null;
  10740. };
  10741. Engine.prototype.createVertexBuffer = function (vertices) {
  10742. var vbo = this._gl.createBuffer();
  10743. if (!vbo) {
  10744. throw new Error("Unable to create vertex buffer");
  10745. }
  10746. this.bindArrayBuffer(vbo);
  10747. if (vertices instanceof Float32Array) {
  10748. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10749. }
  10750. else {
  10751. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10752. }
  10753. this._resetVertexBufferBinding();
  10754. vbo.references = 1;
  10755. return vbo;
  10756. };
  10757. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10758. var vbo = this._gl.createBuffer();
  10759. if (!vbo) {
  10760. throw new Error("Unable to create dynamic vertex buffer");
  10761. }
  10762. this.bindArrayBuffer(vbo);
  10763. if (vertices instanceof Float32Array) {
  10764. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10765. }
  10766. else {
  10767. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10768. }
  10769. this._resetVertexBufferBinding();
  10770. vbo.references = 1;
  10771. return vbo;
  10772. };
  10773. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10774. if (offset === void 0) { offset = 0; }
  10775. // Force cache update
  10776. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10777. this.bindIndexBuffer(indexBuffer);
  10778. var arrayBuffer;
  10779. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10780. arrayBuffer = indices;
  10781. }
  10782. else {
  10783. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10784. }
  10785. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10786. this._resetIndexBufferBinding();
  10787. };
  10788. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10789. this.bindArrayBuffer(vertexBuffer);
  10790. if (offset === undefined) {
  10791. offset = 0;
  10792. }
  10793. if (count === undefined) {
  10794. if (vertices instanceof Float32Array) {
  10795. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10796. }
  10797. else {
  10798. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10799. }
  10800. }
  10801. else {
  10802. if (vertices instanceof Float32Array) {
  10803. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10804. }
  10805. else {
  10806. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10807. }
  10808. }
  10809. this._resetVertexBufferBinding();
  10810. };
  10811. Engine.prototype._resetIndexBufferBinding = function () {
  10812. this.bindIndexBuffer(null);
  10813. this._cachedIndexBuffer = null;
  10814. };
  10815. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10816. var vbo = this._gl.createBuffer();
  10817. if (!vbo) {
  10818. throw new Error("Unable to create index buffer");
  10819. }
  10820. this.bindIndexBuffer(vbo);
  10821. // Check for 32 bits indices
  10822. var arrayBuffer;
  10823. var need32Bits = false;
  10824. if (indices instanceof Uint16Array) {
  10825. arrayBuffer = indices;
  10826. }
  10827. else {
  10828. //check 32 bit support
  10829. if (this._caps.uintIndices) {
  10830. if (indices instanceof Uint32Array) {
  10831. arrayBuffer = indices;
  10832. need32Bits = true;
  10833. }
  10834. else {
  10835. //number[] or Int32Array, check if 32 bit is necessary
  10836. for (var index = 0; index < indices.length; index++) {
  10837. if (indices[index] > 65535) {
  10838. need32Bits = true;
  10839. break;
  10840. }
  10841. }
  10842. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10843. }
  10844. }
  10845. else {
  10846. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10847. arrayBuffer = new Uint16Array(indices);
  10848. }
  10849. }
  10850. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10851. this._resetIndexBufferBinding();
  10852. vbo.references = 1;
  10853. vbo.is32Bits = need32Bits;
  10854. return vbo;
  10855. };
  10856. Engine.prototype.bindArrayBuffer = function (buffer) {
  10857. if (!this._vaoRecordInProgress) {
  10858. this._unbindVertexArrayObject();
  10859. }
  10860. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10861. };
  10862. Engine.prototype.bindUniformBuffer = function (buffer) {
  10863. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10864. };
  10865. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10866. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10867. };
  10868. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10869. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10870. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10871. };
  10872. ;
  10873. Engine.prototype.bindIndexBuffer = function (buffer) {
  10874. if (!this._vaoRecordInProgress) {
  10875. this._unbindVertexArrayObject();
  10876. }
  10877. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10878. };
  10879. Engine.prototype.bindBuffer = function (buffer, target) {
  10880. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10881. this._gl.bindBuffer(target, buffer);
  10882. this._currentBoundBuffer[target] = buffer;
  10883. }
  10884. };
  10885. Engine.prototype.updateArrayBuffer = function (data) {
  10886. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10887. };
  10888. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10889. var pointer = this._currentBufferPointers[indx];
  10890. var changed = false;
  10891. if (!pointer.active) {
  10892. changed = true;
  10893. pointer.active = true;
  10894. pointer.index = indx;
  10895. pointer.size = size;
  10896. pointer.type = type;
  10897. pointer.normalized = normalized;
  10898. pointer.stride = stride;
  10899. pointer.offset = offset;
  10900. pointer.buffer = buffer;
  10901. }
  10902. else {
  10903. if (pointer.buffer !== buffer) {
  10904. pointer.buffer = buffer;
  10905. changed = true;
  10906. }
  10907. if (pointer.size !== size) {
  10908. pointer.size = size;
  10909. changed = true;
  10910. }
  10911. if (pointer.type !== type) {
  10912. pointer.type = type;
  10913. changed = true;
  10914. }
  10915. if (pointer.normalized !== normalized) {
  10916. pointer.normalized = normalized;
  10917. changed = true;
  10918. }
  10919. if (pointer.stride !== stride) {
  10920. pointer.stride = stride;
  10921. changed = true;
  10922. }
  10923. if (pointer.offset !== offset) {
  10924. pointer.offset = offset;
  10925. changed = true;
  10926. }
  10927. }
  10928. if (changed || this._vaoRecordInProgress) {
  10929. this.bindArrayBuffer(buffer);
  10930. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10931. }
  10932. };
  10933. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10934. if (indexBuffer == null) {
  10935. return;
  10936. }
  10937. if (this._cachedIndexBuffer !== indexBuffer) {
  10938. this._cachedIndexBuffer = indexBuffer;
  10939. this.bindIndexBuffer(indexBuffer);
  10940. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10941. }
  10942. };
  10943. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10944. var attributes = effect.getAttributesNames();
  10945. if (!this._vaoRecordInProgress) {
  10946. this._unbindVertexArrayObject();
  10947. }
  10948. this.unbindAllAttributes();
  10949. for (var index = 0; index < attributes.length; index++) {
  10950. var order = effect.getAttributeLocation(index);
  10951. if (order >= 0) {
  10952. var vertexBuffer = vertexBuffers[attributes[index]];
  10953. if (!vertexBuffer) {
  10954. continue;
  10955. }
  10956. this._gl.enableVertexAttribArray(order);
  10957. if (!this._vaoRecordInProgress) {
  10958. this._vertexAttribArraysEnabled[order] = true;
  10959. }
  10960. var buffer = vertexBuffer.getBuffer();
  10961. if (buffer) {
  10962. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10963. if (vertexBuffer.getIsInstanced()) {
  10964. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10965. if (!this._vaoRecordInProgress) {
  10966. this._currentInstanceLocations.push(order);
  10967. this._currentInstanceBuffers.push(buffer);
  10968. }
  10969. }
  10970. }
  10971. }
  10972. }
  10973. };
  10974. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10975. var vao = this._gl.createVertexArray();
  10976. this._vaoRecordInProgress = true;
  10977. this._gl.bindVertexArray(vao);
  10978. this._mustWipeVertexAttributes = true;
  10979. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10980. this.bindIndexBuffer(indexBuffer);
  10981. this._vaoRecordInProgress = false;
  10982. this._gl.bindVertexArray(null);
  10983. return vao;
  10984. };
  10985. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10986. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10987. this._cachedVertexArrayObject = vertexArrayObject;
  10988. this._gl.bindVertexArray(vertexArrayObject);
  10989. this._cachedVertexBuffers = null;
  10990. this._cachedIndexBuffer = null;
  10991. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10992. this._mustWipeVertexAttributes = true;
  10993. }
  10994. };
  10995. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10996. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10997. this._cachedVertexBuffers = vertexBuffer;
  10998. this._cachedEffectForVertexBuffers = effect;
  10999. var attributesCount = effect.getAttributesCount();
  11000. this._unbindVertexArrayObject();
  11001. this.unbindAllAttributes();
  11002. var offset = 0;
  11003. for (var index = 0; index < attributesCount; index++) {
  11004. if (index < vertexDeclaration.length) {
  11005. var order = effect.getAttributeLocation(index);
  11006. if (order >= 0) {
  11007. this._gl.enableVertexAttribArray(order);
  11008. this._vertexAttribArraysEnabled[order] = true;
  11009. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11010. }
  11011. offset += vertexDeclaration[index] * 4;
  11012. }
  11013. }
  11014. }
  11015. this._bindIndexBufferWithCache(indexBuffer);
  11016. };
  11017. Engine.prototype._unbindVertexArrayObject = function () {
  11018. if (!this._cachedVertexArrayObject) {
  11019. return;
  11020. }
  11021. this._cachedVertexArrayObject = null;
  11022. this._gl.bindVertexArray(null);
  11023. };
  11024. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11025. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11026. this._cachedVertexBuffers = vertexBuffers;
  11027. this._cachedEffectForVertexBuffers = effect;
  11028. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11029. }
  11030. this._bindIndexBufferWithCache(indexBuffer);
  11031. };
  11032. Engine.prototype.unbindInstanceAttributes = function () {
  11033. var boundBuffer;
  11034. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11035. var instancesBuffer = this._currentInstanceBuffers[i];
  11036. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11037. boundBuffer = instancesBuffer;
  11038. this.bindArrayBuffer(instancesBuffer);
  11039. }
  11040. var offsetLocation = this._currentInstanceLocations[i];
  11041. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11042. }
  11043. this._currentInstanceBuffers.length = 0;
  11044. this._currentInstanceLocations.length = 0;
  11045. };
  11046. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11047. this._gl.deleteVertexArray(vao);
  11048. };
  11049. Engine.prototype._releaseBuffer = function (buffer) {
  11050. buffer.references--;
  11051. if (buffer.references === 0) {
  11052. this._gl.deleteBuffer(buffer);
  11053. return true;
  11054. }
  11055. return false;
  11056. };
  11057. Engine.prototype.createInstancesBuffer = function (capacity) {
  11058. var buffer = this._gl.createBuffer();
  11059. if (!buffer) {
  11060. throw new Error("Unable to create instance buffer");
  11061. }
  11062. buffer.capacity = capacity;
  11063. this.bindArrayBuffer(buffer);
  11064. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11065. return buffer;
  11066. };
  11067. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11068. this._gl.deleteBuffer(buffer);
  11069. };
  11070. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11071. this.bindArrayBuffer(instancesBuffer);
  11072. if (data) {
  11073. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11074. }
  11075. if (offsetLocations[0].index !== undefined) {
  11076. var stride = 0;
  11077. for (var i = 0; i < offsetLocations.length; i++) {
  11078. var ai = offsetLocations[i];
  11079. stride += ai.attributeSize * 4;
  11080. }
  11081. for (var i = 0; i < offsetLocations.length; i++) {
  11082. var ai = offsetLocations[i];
  11083. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11084. this._gl.enableVertexAttribArray(ai.index);
  11085. this._vertexAttribArraysEnabled[ai.index] = true;
  11086. }
  11087. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11088. this._gl.vertexAttribDivisor(ai.index, 1);
  11089. this._currentInstanceLocations.push(ai.index);
  11090. this._currentInstanceBuffers.push(instancesBuffer);
  11091. }
  11092. }
  11093. else {
  11094. for (var index = 0; index < 4; index++) {
  11095. var offsetLocation = offsetLocations[index];
  11096. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11097. this._gl.enableVertexAttribArray(offsetLocation);
  11098. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11099. }
  11100. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11101. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11102. this._currentInstanceLocations.push(offsetLocation);
  11103. this._currentInstanceBuffers.push(instancesBuffer);
  11104. }
  11105. }
  11106. };
  11107. Engine.prototype.applyStates = function () {
  11108. this._depthCullingState.apply(this._gl);
  11109. this._stencilState.apply(this._gl);
  11110. this._alphaState.apply(this._gl);
  11111. };
  11112. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11113. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11114. };
  11115. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11116. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11117. };
  11118. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11119. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11120. };
  11121. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11122. // Apply states
  11123. this.applyStates();
  11124. this._drawCalls.addCount(1, false);
  11125. // Render
  11126. var drawMode = this.DrawMode(fillMode);
  11127. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11128. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11129. if (instancesCount) {
  11130. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11131. }
  11132. else {
  11133. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11134. }
  11135. };
  11136. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11137. // Apply states
  11138. this.applyStates();
  11139. this._drawCalls.addCount(1, false);
  11140. var drawMode = this.DrawMode(fillMode);
  11141. if (instancesCount) {
  11142. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11143. }
  11144. else {
  11145. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11146. }
  11147. };
  11148. Engine.prototype.DrawMode = function (fillMode) {
  11149. switch (fillMode) {
  11150. // Triangle views
  11151. case BABYLON.Material.TriangleFillMode:
  11152. return this._gl.TRIANGLES;
  11153. case BABYLON.Material.PointFillMode:
  11154. return this._gl.POINTS;
  11155. case BABYLON.Material.WireFrameFillMode:
  11156. return this._gl.LINES;
  11157. // Draw modes
  11158. case BABYLON.Material.PointListDrawMode:
  11159. return this._gl.POINTS;
  11160. case BABYLON.Material.LineListDrawMode:
  11161. return this._gl.LINES;
  11162. case BABYLON.Material.LineLoopDrawMode:
  11163. return this._gl.LINE_LOOP;
  11164. case BABYLON.Material.LineStripDrawMode:
  11165. return this._gl.LINE_STRIP;
  11166. case BABYLON.Material.TriangleStripDrawMode:
  11167. return this._gl.TRIANGLE_STRIP;
  11168. case BABYLON.Material.TriangleFanDrawMode:
  11169. return this._gl.TRIANGLE_FAN;
  11170. default:
  11171. return this._gl.TRIANGLES;
  11172. }
  11173. };
  11174. // Shaders
  11175. Engine.prototype._releaseEffect = function (effect) {
  11176. if (this._compiledEffects[effect._key]) {
  11177. delete this._compiledEffects[effect._key];
  11178. this._deleteProgram(effect.getProgram());
  11179. }
  11180. };
  11181. Engine.prototype._deleteProgram = function (program) {
  11182. if (program) {
  11183. program.__SPECTOR_rebuildProgram = null;
  11184. if (program.transformFeedback) {
  11185. this.deleteTransformFeedback(program.transformFeedback);
  11186. program.transformFeedback = null;
  11187. }
  11188. this._gl.deleteProgram(program);
  11189. }
  11190. };
  11191. /**
  11192. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11193. * @param samplers An array of string used to represent textures
  11194. */
  11195. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11196. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11197. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11198. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11199. if (this._compiledEffects[name]) {
  11200. var compiledEffect = this._compiledEffects[name];
  11201. if (onCompiled && compiledEffect.isReady()) {
  11202. onCompiled(compiledEffect);
  11203. }
  11204. return compiledEffect;
  11205. }
  11206. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11207. effect._key = name;
  11208. this._compiledEffects[name] = effect;
  11209. return effect;
  11210. };
  11211. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11212. if (uniformsNames === void 0) { uniformsNames = []; }
  11213. if (samplers === void 0) { samplers = []; }
  11214. if (defines === void 0) { defines = ""; }
  11215. return this.createEffect({
  11216. vertex: "particles",
  11217. fragmentElement: fragmentName
  11218. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11219. };
  11220. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11221. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11222. context = context || this._gl;
  11223. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11224. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11225. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11226. };
  11227. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11228. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11229. context = context || this._gl;
  11230. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11231. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11232. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11233. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11234. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11235. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11236. return program;
  11237. };
  11238. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11239. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11240. var shaderProgram = context.createProgram();
  11241. if (!shaderProgram) {
  11242. throw new Error("Unable to create program");
  11243. }
  11244. context.attachShader(shaderProgram, vertexShader);
  11245. context.attachShader(shaderProgram, fragmentShader);
  11246. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11247. var transformFeedback = this.createTransformFeedback();
  11248. this.bindTransformFeedback(transformFeedback);
  11249. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11250. shaderProgram.transformFeedback = transformFeedback;
  11251. }
  11252. context.linkProgram(shaderProgram);
  11253. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11254. this.bindTransformFeedback(null);
  11255. }
  11256. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11257. if (!linked) {
  11258. context.validateProgram(shaderProgram);
  11259. var error = context.getProgramInfoLog(shaderProgram);
  11260. if (error) {
  11261. throw new Error(error);
  11262. }
  11263. }
  11264. context.deleteShader(vertexShader);
  11265. context.deleteShader(fragmentShader);
  11266. return shaderProgram;
  11267. };
  11268. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11269. var results = new Array();
  11270. for (var index = 0; index < uniformsNames.length; index++) {
  11271. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11272. }
  11273. return results;
  11274. };
  11275. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11276. var results = [];
  11277. for (var index = 0; index < attributesNames.length; index++) {
  11278. try {
  11279. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11280. }
  11281. catch (e) {
  11282. results.push(-1);
  11283. }
  11284. }
  11285. return results;
  11286. };
  11287. Engine.prototype.enableEffect = function (effect) {
  11288. if (!effect) {
  11289. return;
  11290. }
  11291. // Use program
  11292. this.bindSamplers(effect);
  11293. this._currentEffect = effect;
  11294. if (effect.onBind) {
  11295. effect.onBind(effect);
  11296. }
  11297. effect.onBindObservable.notifyObservers(effect);
  11298. };
  11299. Engine.prototype.setIntArray = function (uniform, array) {
  11300. if (!uniform)
  11301. return;
  11302. this._gl.uniform1iv(uniform, array);
  11303. };
  11304. Engine.prototype.setIntArray2 = function (uniform, array) {
  11305. if (!uniform || array.length % 2 !== 0)
  11306. return;
  11307. this._gl.uniform2iv(uniform, array);
  11308. };
  11309. Engine.prototype.setIntArray3 = function (uniform, array) {
  11310. if (!uniform || array.length % 3 !== 0)
  11311. return;
  11312. this._gl.uniform3iv(uniform, array);
  11313. };
  11314. Engine.prototype.setIntArray4 = function (uniform, array) {
  11315. if (!uniform || array.length % 4 !== 0)
  11316. return;
  11317. this._gl.uniform4iv(uniform, array);
  11318. };
  11319. Engine.prototype.setFloatArray = function (uniform, array) {
  11320. if (!uniform)
  11321. return;
  11322. this._gl.uniform1fv(uniform, array);
  11323. };
  11324. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11325. if (!uniform || array.length % 2 !== 0)
  11326. return;
  11327. this._gl.uniform2fv(uniform, array);
  11328. };
  11329. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11330. if (!uniform || array.length % 3 !== 0)
  11331. return;
  11332. this._gl.uniform3fv(uniform, array);
  11333. };
  11334. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11335. if (!uniform || array.length % 4 !== 0)
  11336. return;
  11337. this._gl.uniform4fv(uniform, array);
  11338. };
  11339. Engine.prototype.setArray = function (uniform, array) {
  11340. if (!uniform)
  11341. return;
  11342. this._gl.uniform1fv(uniform, array);
  11343. };
  11344. Engine.prototype.setArray2 = function (uniform, array) {
  11345. if (!uniform || array.length % 2 !== 0)
  11346. return;
  11347. this._gl.uniform2fv(uniform, array);
  11348. };
  11349. Engine.prototype.setArray3 = function (uniform, array) {
  11350. if (!uniform || array.length % 3 !== 0)
  11351. return;
  11352. this._gl.uniform3fv(uniform, array);
  11353. };
  11354. Engine.prototype.setArray4 = function (uniform, array) {
  11355. if (!uniform || array.length % 4 !== 0)
  11356. return;
  11357. this._gl.uniform4fv(uniform, array);
  11358. };
  11359. Engine.prototype.setMatrices = function (uniform, matrices) {
  11360. if (!uniform)
  11361. return;
  11362. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11363. };
  11364. Engine.prototype.setMatrix = function (uniform, matrix) {
  11365. if (!uniform)
  11366. return;
  11367. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11368. };
  11369. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11370. if (!uniform)
  11371. return;
  11372. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11373. };
  11374. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11375. if (!uniform)
  11376. return;
  11377. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11378. };
  11379. Engine.prototype.setInt = function (uniform, value) {
  11380. if (!uniform)
  11381. return;
  11382. this._gl.uniform1i(uniform, value);
  11383. };
  11384. Engine.prototype.setFloat = function (uniform, value) {
  11385. if (!uniform)
  11386. return;
  11387. this._gl.uniform1f(uniform, value);
  11388. };
  11389. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11390. if (!uniform)
  11391. return;
  11392. this._gl.uniform2f(uniform, x, y);
  11393. };
  11394. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11395. if (!uniform)
  11396. return;
  11397. this._gl.uniform3f(uniform, x, y, z);
  11398. };
  11399. Engine.prototype.setBool = function (uniform, bool) {
  11400. if (!uniform)
  11401. return;
  11402. this._gl.uniform1i(uniform, bool);
  11403. };
  11404. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11405. if (!uniform)
  11406. return;
  11407. this._gl.uniform4f(uniform, x, y, z, w);
  11408. };
  11409. Engine.prototype.setColor3 = function (uniform, color3) {
  11410. if (!uniform)
  11411. return;
  11412. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11413. };
  11414. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11415. if (!uniform)
  11416. return;
  11417. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11418. };
  11419. // States
  11420. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11421. if (zOffset === void 0) { zOffset = 0; }
  11422. if (reverseSide === void 0) { reverseSide = false; }
  11423. // Culling
  11424. if (this._depthCullingState.cull !== culling || force) {
  11425. this._depthCullingState.cull = culling;
  11426. }
  11427. // Cull face
  11428. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11429. if (this._depthCullingState.cullFace !== cullFace || force) {
  11430. this._depthCullingState.cullFace = cullFace;
  11431. }
  11432. // Z offset
  11433. this.setZOffset(zOffset);
  11434. // Front face
  11435. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11436. if (this._depthCullingState.frontFace !== frontFace || force) {
  11437. this._depthCullingState.frontFace = frontFace;
  11438. }
  11439. };
  11440. Engine.prototype.setZOffset = function (value) {
  11441. this._depthCullingState.zOffset = value;
  11442. };
  11443. Engine.prototype.getZOffset = function () {
  11444. return this._depthCullingState.zOffset;
  11445. };
  11446. Engine.prototype.setDepthBuffer = function (enable) {
  11447. this._depthCullingState.depthTest = enable;
  11448. };
  11449. Engine.prototype.getDepthWrite = function () {
  11450. return this._depthCullingState.depthMask;
  11451. };
  11452. Engine.prototype.setDepthWrite = function (enable) {
  11453. this._depthCullingState.depthMask = enable;
  11454. };
  11455. Engine.prototype.setColorWrite = function (enable) {
  11456. this._gl.colorMask(enable, enable, enable, enable);
  11457. this._colorWrite = enable;
  11458. };
  11459. Engine.prototype.getColorWrite = function () {
  11460. return this._colorWrite;
  11461. };
  11462. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11463. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11464. };
  11465. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11466. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11467. if (this._alphaMode === mode) {
  11468. return;
  11469. }
  11470. switch (mode) {
  11471. case Engine.ALPHA_DISABLE:
  11472. this._alphaState.alphaBlend = false;
  11473. break;
  11474. case Engine.ALPHA_PREMULTIPLIED:
  11475. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11476. this._alphaState.alphaBlend = true;
  11477. break;
  11478. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11479. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11480. this._alphaState.alphaBlend = true;
  11481. break;
  11482. case Engine.ALPHA_COMBINE:
  11483. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11484. this._alphaState.alphaBlend = true;
  11485. break;
  11486. case Engine.ALPHA_ONEONE:
  11487. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11488. this._alphaState.alphaBlend = true;
  11489. break;
  11490. case Engine.ALPHA_ADD:
  11491. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11492. this._alphaState.alphaBlend = true;
  11493. break;
  11494. case Engine.ALPHA_SUBTRACT:
  11495. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11496. this._alphaState.alphaBlend = true;
  11497. break;
  11498. case Engine.ALPHA_MULTIPLY:
  11499. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11500. this._alphaState.alphaBlend = true;
  11501. break;
  11502. case Engine.ALPHA_MAXIMIZED:
  11503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11504. this._alphaState.alphaBlend = true;
  11505. break;
  11506. case Engine.ALPHA_INTERPOLATE:
  11507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11508. this._alphaState.alphaBlend = true;
  11509. break;
  11510. case Engine.ALPHA_SCREENMODE:
  11511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11512. this._alphaState.alphaBlend = true;
  11513. break;
  11514. }
  11515. if (!noDepthWriteChange) {
  11516. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11517. }
  11518. this._alphaMode = mode;
  11519. };
  11520. Engine.prototype.getAlphaMode = function () {
  11521. return this._alphaMode;
  11522. };
  11523. // Textures
  11524. Engine.prototype.wipeCaches = function (bruteForce) {
  11525. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11526. return;
  11527. }
  11528. this._currentEffect = null;
  11529. // 6/8/2017: deltakosh: Should not be required anymore.
  11530. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11531. if (bruteForce) {
  11532. this.resetTextureCache();
  11533. this._currentProgram = null;
  11534. this._stencilState.reset();
  11535. this._depthCullingState.reset();
  11536. this.setDepthFunctionToLessOrEqual();
  11537. this._alphaState.reset();
  11538. }
  11539. this._resetVertexBufferBinding();
  11540. this._cachedIndexBuffer = null;
  11541. this._cachedEffectForVertexBuffers = null;
  11542. this._unbindVertexArrayObject();
  11543. this.bindIndexBuffer(null);
  11544. };
  11545. /**
  11546. * Set the compressed texture format to use, based on the formats you have, and the formats
  11547. * supported by the hardware / browser.
  11548. *
  11549. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11550. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11551. * to API arguments needed to compressed textures. This puts the burden on the container
  11552. * generator to house the arcane code for determining these for current & future formats.
  11553. *
  11554. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11555. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11556. *
  11557. * Note: The result of this call is not taken into account when a texture is base64.
  11558. *
  11559. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11560. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11561. *
  11562. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11563. * @returns The extension selected.
  11564. */
  11565. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11566. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11567. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11568. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11569. return this._textureFormatInUse = this._texturesSupported[i];
  11570. }
  11571. }
  11572. }
  11573. // actively set format to nothing, to allow this to be called more than once
  11574. // and possibly fail the 2nd time
  11575. this._textureFormatInUse = null;
  11576. return null;
  11577. };
  11578. Engine.prototype._createTexture = function () {
  11579. var texture = this._gl.createTexture();
  11580. if (!texture) {
  11581. throw new Error("Unable to create texture");
  11582. }
  11583. return texture;
  11584. };
  11585. /**
  11586. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11587. * @param {string} urlArg- This contains one of the following:
  11588. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11589. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11590. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11591. *
  11592. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11593. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11594. * @param {Scene} scene- Needed for loading to the correct scene.
  11595. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11596. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11597. * @param {callback} onError- Optional callback to be called upon failure.
  11598. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11599. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11600. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11601. *
  11602. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11603. */
  11604. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11605. var _this = this;
  11606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11607. if (onLoad === void 0) { onLoad = null; }
  11608. if (onError === void 0) { onError = null; }
  11609. if (buffer === void 0) { buffer = null; }
  11610. if (fallBack === void 0) { fallBack = null; }
  11611. if (format === void 0) { format = null; }
  11612. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11613. var fromData = url.substr(0, 5) === "data:";
  11614. var fromBlob = url.substr(0, 5) === "blob:";
  11615. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11616. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11617. // establish the file extension, if possible
  11618. var lastDot = url.lastIndexOf('.');
  11619. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11620. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11621. var isTGA = (extension === ".tga");
  11622. // determine if a ktx file should be substituted
  11623. var isKTX = false;
  11624. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11625. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11626. isKTX = true;
  11627. }
  11628. if (scene) {
  11629. scene._addPendingData(texture);
  11630. }
  11631. texture.url = url;
  11632. texture.generateMipMaps = !noMipmap;
  11633. texture.samplingMode = samplingMode;
  11634. texture.invertY = invertY;
  11635. if (!this._doNotHandleContextLost) {
  11636. // Keep a link to the buffer only if we plan to handle context lost
  11637. texture._buffer = buffer;
  11638. }
  11639. var onLoadObserver = null;
  11640. if (onLoad && !fallBack) {
  11641. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11642. }
  11643. if (!fallBack)
  11644. this._internalTexturesCache.push(texture);
  11645. var onerror = function (message, exception) {
  11646. if (scene) {
  11647. scene._removePendingData(texture);
  11648. }
  11649. if (onLoadObserver) {
  11650. texture.onLoadedObservable.remove(onLoadObserver);
  11651. }
  11652. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11653. if (isKTX) {
  11654. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11655. }
  11656. else if (BABYLON.Tools.UseFallbackTexture) {
  11657. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11658. }
  11659. if (onError) {
  11660. onError(message || "Unknown error", exception);
  11661. }
  11662. };
  11663. var callback = null;
  11664. // processing for non-image formats
  11665. if (isKTX || isTGA || isDDS) {
  11666. if (isKTX) {
  11667. callback = function (data) {
  11668. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11669. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11670. ktx.uploadLevels(_this._gl, !noMipmap);
  11671. return false;
  11672. }, samplingMode);
  11673. };
  11674. }
  11675. else if (isTGA) {
  11676. callback = function (arrayBuffer) {
  11677. var data = new Uint8Array(arrayBuffer);
  11678. var header = BABYLON.TGATools.GetTGAHeader(data);
  11679. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11680. BABYLON.TGATools.UploadContent(_this._gl, data);
  11681. return false;
  11682. }, samplingMode);
  11683. };
  11684. }
  11685. else if (isDDS) {
  11686. callback = function (data) {
  11687. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11688. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11689. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11690. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11691. return false;
  11692. }, samplingMode);
  11693. };
  11694. }
  11695. if (!buffer) {
  11696. this._loadFile(url, function (data) {
  11697. if (callback) {
  11698. callback(data);
  11699. }
  11700. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11701. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11702. });
  11703. }
  11704. else {
  11705. if (callback) {
  11706. callback(buffer);
  11707. }
  11708. }
  11709. // image format processing
  11710. }
  11711. else {
  11712. var onload = function (img) {
  11713. if (fromBlob && !_this._doNotHandleContextLost) {
  11714. // We need to store the image if we need to rebuild the texture
  11715. // in case of a webgl context lost
  11716. texture._buffer = img;
  11717. }
  11718. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11719. var gl = _this._gl;
  11720. var isPot = (img.width === potWidth && img.height === potHeight);
  11721. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11722. if (isPot) {
  11723. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11724. return false;
  11725. }
  11726. // Using shaders to rescale because canvas.drawImage is lossy
  11727. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11728. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11729. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11730. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11734. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11735. _this._releaseTexture(source);
  11736. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11737. continuationCallback();
  11738. });
  11739. return true;
  11740. }, samplingMode);
  11741. };
  11742. if (!fromData || isBase64)
  11743. if (buffer instanceof HTMLImageElement) {
  11744. onload(buffer);
  11745. }
  11746. else {
  11747. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11748. }
  11749. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11750. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11751. else
  11752. onload(buffer);
  11753. }
  11754. return texture;
  11755. };
  11756. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11757. var _this = this;
  11758. var rtt = this.createRenderTargetTexture({
  11759. width: destination.width,
  11760. height: destination.height,
  11761. }, {
  11762. generateMipMaps: false,
  11763. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11764. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11765. generateDepthBuffer: false,
  11766. generateStencilBuffer: false
  11767. });
  11768. if (!this._rescalePostProcess) {
  11769. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11770. }
  11771. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11772. _this._rescalePostProcess.onApply = function (effect) {
  11773. effect._bindTexture("textureSampler", source);
  11774. };
  11775. var hostingScene = scene;
  11776. if (!hostingScene) {
  11777. hostingScene = _this.scenes[_this.scenes.length - 1];
  11778. }
  11779. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11780. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11781. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11782. _this.unBindFramebuffer(rtt);
  11783. _this._releaseTexture(rtt);
  11784. if (onComplete) {
  11785. onComplete();
  11786. }
  11787. });
  11788. };
  11789. Engine.prototype._getInternalFormat = function (format) {
  11790. var internalFormat = this._gl.RGBA;
  11791. switch (format) {
  11792. case Engine.TEXTUREFORMAT_ALPHA:
  11793. internalFormat = this._gl.ALPHA;
  11794. break;
  11795. case Engine.TEXTUREFORMAT_LUMINANCE:
  11796. internalFormat = this._gl.LUMINANCE;
  11797. break;
  11798. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11799. internalFormat = this._gl.LUMINANCE_ALPHA;
  11800. break;
  11801. case Engine.TEXTUREFORMAT_RGB:
  11802. internalFormat = this._gl.RGB;
  11803. break;
  11804. case Engine.TEXTUREFORMAT_RGBA:
  11805. internalFormat = this._gl.RGBA;
  11806. break;
  11807. }
  11808. return internalFormat;
  11809. };
  11810. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11811. if (compression === void 0) { compression = null; }
  11812. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11813. if (!texture) {
  11814. return;
  11815. }
  11816. var internalFormat = this._getInternalFormat(format);
  11817. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11818. var textureType = this._getWebGLTextureType(type);
  11819. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11820. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11821. if (!this._doNotHandleContextLost) {
  11822. texture._bufferView = data;
  11823. texture.format = format;
  11824. texture.type = type;
  11825. texture.invertY = invertY;
  11826. texture._compression = compression;
  11827. }
  11828. if (texture.width % 4 !== 0) {
  11829. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11830. }
  11831. if (compression && data) {
  11832. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11833. }
  11834. else {
  11835. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11836. }
  11837. if (texture.generateMipMaps) {
  11838. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11839. }
  11840. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11841. // this.resetTextureCache();
  11842. texture.isReady = true;
  11843. };
  11844. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11845. if (compression === void 0) { compression = null; }
  11846. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11847. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11848. texture.baseWidth = width;
  11849. texture.baseHeight = height;
  11850. texture.width = width;
  11851. texture.height = height;
  11852. texture.format = format;
  11853. texture.generateMipMaps = generateMipMaps;
  11854. texture.samplingMode = samplingMode;
  11855. texture.invertY = invertY;
  11856. texture._compression = compression;
  11857. texture.type = type;
  11858. if (!this._doNotHandleContextLost) {
  11859. texture._bufferView = data;
  11860. }
  11861. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11862. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11863. // Filters
  11864. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11865. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11866. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11867. if (generateMipMaps) {
  11868. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11869. }
  11870. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11871. this._internalTexturesCache.push(texture);
  11872. return texture;
  11873. };
  11874. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11875. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11876. texture.baseWidth = width;
  11877. texture.baseHeight = height;
  11878. if (generateMipMaps) {
  11879. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11880. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11881. }
  11882. // this.resetTextureCache();
  11883. texture.width = width;
  11884. texture.height = height;
  11885. texture.isReady = false;
  11886. texture.generateMipMaps = generateMipMaps;
  11887. texture.samplingMode = samplingMode;
  11888. this.updateTextureSamplingMode(samplingMode, texture);
  11889. this._internalTexturesCache.push(texture);
  11890. return texture;
  11891. };
  11892. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11893. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11894. if (texture.isCube) {
  11895. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11896. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11897. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11898. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11899. }
  11900. else if (texture.is3D) {
  11901. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11902. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11903. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11904. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11905. }
  11906. else {
  11907. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11908. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11909. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11910. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11911. }
  11912. texture.samplingMode = samplingMode;
  11913. };
  11914. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11915. if (premulAlpha === void 0) { premulAlpha = false; }
  11916. if (!texture) {
  11917. return;
  11918. }
  11919. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11920. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11921. if (premulAlpha) {
  11922. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11923. }
  11924. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11925. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11926. if (texture.generateMipMaps) {
  11927. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11928. }
  11929. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11930. if (premulAlpha) {
  11931. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11932. }
  11933. texture.isReady = true;
  11934. };
  11935. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11936. if (!texture || texture._isDisabled) {
  11937. return;
  11938. }
  11939. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11940. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11941. try {
  11942. // Testing video texture support
  11943. if (this._videoTextureSupported === undefined) {
  11944. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11945. if (this._gl.getError() !== 0) {
  11946. this._videoTextureSupported = false;
  11947. }
  11948. else {
  11949. this._videoTextureSupported = true;
  11950. }
  11951. }
  11952. // Copy video through the current working canvas if video texture is not supported
  11953. if (!this._videoTextureSupported) {
  11954. if (!texture._workingCanvas) {
  11955. texture._workingCanvas = document.createElement("canvas");
  11956. var context = texture._workingCanvas.getContext("2d");
  11957. if (!context) {
  11958. throw new Error("Unable to get 2d context");
  11959. }
  11960. texture._workingContext = context;
  11961. texture._workingCanvas.width = texture.width;
  11962. texture._workingCanvas.height = texture.height;
  11963. }
  11964. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11965. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11966. }
  11967. else {
  11968. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11969. }
  11970. if (texture.generateMipMaps) {
  11971. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11972. }
  11973. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11974. // this.resetTextureCache();
  11975. texture.isReady = true;
  11976. }
  11977. catch (ex) {
  11978. // Something unexpected
  11979. // Let's disable the texture
  11980. texture._isDisabled = true;
  11981. }
  11982. };
  11983. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11984. var fullOptions = new RenderTargetCreationOptions();
  11985. if (options !== undefined && typeof options === "object") {
  11986. fullOptions.generateMipMaps = options.generateMipMaps;
  11987. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11988. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11989. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11990. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11991. }
  11992. else {
  11993. fullOptions.generateMipMaps = options;
  11994. fullOptions.generateDepthBuffer = true;
  11995. fullOptions.generateStencilBuffer = false;
  11996. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11997. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11998. }
  11999. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12000. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12001. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12002. }
  12003. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12004. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12005. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12006. }
  12007. var gl = this._gl;
  12008. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12009. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12010. var width = size.width || size;
  12011. var height = size.height || size;
  12012. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12013. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12014. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12015. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12016. }
  12017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12021. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12022. // Create the framebuffer
  12023. var framebuffer = gl.createFramebuffer();
  12024. this.bindUnboundFramebuffer(framebuffer);
  12025. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12026. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12027. if (fullOptions.generateMipMaps) {
  12028. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12029. }
  12030. // Unbind
  12031. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12032. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12033. this.bindUnboundFramebuffer(null);
  12034. texture._framebuffer = framebuffer;
  12035. texture.baseWidth = width;
  12036. texture.baseHeight = height;
  12037. texture.width = width;
  12038. texture.height = height;
  12039. texture.isReady = true;
  12040. texture.samples = 1;
  12041. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12042. texture.samplingMode = fullOptions.samplingMode;
  12043. texture.type = fullOptions.type;
  12044. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12045. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12046. // this.resetTextureCache();
  12047. this._internalTexturesCache.push(texture);
  12048. return texture;
  12049. };
  12050. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12051. var generateMipMaps = false;
  12052. var generateDepthBuffer = true;
  12053. var generateStencilBuffer = false;
  12054. var generateDepthTexture = false;
  12055. var textureCount = 1;
  12056. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12057. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12058. var types = [], samplingModes = [];
  12059. if (options !== undefined) {
  12060. generateMipMaps = options.generateMipMaps;
  12061. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12062. generateStencilBuffer = options.generateStencilBuffer;
  12063. generateDepthTexture = options.generateDepthTexture;
  12064. textureCount = options.textureCount || 1;
  12065. if (options.types) {
  12066. types = options.types;
  12067. }
  12068. if (options.samplingModes) {
  12069. samplingModes = options.samplingModes;
  12070. }
  12071. }
  12072. var gl = this._gl;
  12073. // Create the framebuffer
  12074. var framebuffer = gl.createFramebuffer();
  12075. this.bindUnboundFramebuffer(framebuffer);
  12076. var width = size.width || size;
  12077. var height = size.height || size;
  12078. var textures = [];
  12079. var attachments = [];
  12080. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12081. for (var i = 0; i < textureCount; i++) {
  12082. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12083. var type = types[i] || defaultType;
  12084. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12085. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12086. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12087. }
  12088. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12089. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12090. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12091. }
  12092. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12093. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12094. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12095. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12096. }
  12097. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12098. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12099. textures.push(texture);
  12100. attachments.push(attachment);
  12101. gl.activeTexture(gl["TEXTURE" + i]);
  12102. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12103. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12107. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12108. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12109. if (generateMipMaps) {
  12110. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12111. }
  12112. // Unbind
  12113. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12114. texture._framebuffer = framebuffer;
  12115. texture._depthStencilBuffer = depthStencilBuffer;
  12116. texture.baseWidth = width;
  12117. texture.baseHeight = height;
  12118. texture.width = width;
  12119. texture.height = height;
  12120. texture.isReady = true;
  12121. texture.samples = 1;
  12122. texture.generateMipMaps = generateMipMaps;
  12123. texture.samplingMode = samplingMode;
  12124. texture.type = type;
  12125. texture._generateDepthBuffer = generateDepthBuffer;
  12126. texture._generateStencilBuffer = generateStencilBuffer;
  12127. texture._attachments = attachments;
  12128. this._internalTexturesCache.push(texture);
  12129. }
  12130. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12131. // Depth texture
  12132. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12133. gl.activeTexture(gl.TEXTURE0);
  12134. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12138. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12139. 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);
  12140. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12141. depthTexture._framebuffer = framebuffer;
  12142. depthTexture.baseWidth = width;
  12143. depthTexture.baseHeight = height;
  12144. depthTexture.width = width;
  12145. depthTexture.height = height;
  12146. depthTexture.isReady = true;
  12147. depthTexture.samples = 1;
  12148. depthTexture.generateMipMaps = generateMipMaps;
  12149. depthTexture.samplingMode = gl.NEAREST;
  12150. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12151. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12152. textures.push(depthTexture);
  12153. this._internalTexturesCache.push(depthTexture);
  12154. }
  12155. gl.drawBuffers(attachments);
  12156. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12157. this.bindUnboundFramebuffer(null);
  12158. this.resetTextureCache();
  12159. return textures;
  12160. };
  12161. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12162. if (samples === void 0) { samples = 1; }
  12163. var depthStencilBuffer = null;
  12164. var gl = this._gl;
  12165. // Create the depth/stencil buffer
  12166. if (generateStencilBuffer) {
  12167. depthStencilBuffer = gl.createRenderbuffer();
  12168. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12169. if (samples > 1) {
  12170. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12171. }
  12172. else {
  12173. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12174. }
  12175. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12176. }
  12177. else if (generateDepthBuffer) {
  12178. depthStencilBuffer = gl.createRenderbuffer();
  12179. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12180. if (samples > 1) {
  12181. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12182. }
  12183. else {
  12184. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12185. }
  12186. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12187. }
  12188. return depthStencilBuffer;
  12189. };
  12190. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12191. if (this.webGLVersion < 2 || !texture) {
  12192. return 1;
  12193. }
  12194. if (texture.samples === samples) {
  12195. return samples;
  12196. }
  12197. var gl = this._gl;
  12198. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12199. // Dispose previous render buffers
  12200. if (texture._depthStencilBuffer) {
  12201. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12202. texture._depthStencilBuffer = null;
  12203. }
  12204. if (texture._MSAAFramebuffer) {
  12205. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12206. texture._MSAAFramebuffer = null;
  12207. }
  12208. if (texture._MSAARenderBuffer) {
  12209. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12210. texture._MSAARenderBuffer = null;
  12211. }
  12212. if (samples > 1) {
  12213. var framebuffer = gl.createFramebuffer();
  12214. if (!framebuffer) {
  12215. throw new Error("Unable to create multi sampled framebuffer");
  12216. }
  12217. texture._MSAAFramebuffer = framebuffer;
  12218. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12219. var colorRenderbuffer = gl.createRenderbuffer();
  12220. if (!colorRenderbuffer) {
  12221. throw new Error("Unable to create multi sampled framebuffer");
  12222. }
  12223. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12224. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12225. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12226. texture._MSAARenderBuffer = colorRenderbuffer;
  12227. }
  12228. else {
  12229. this.bindUnboundFramebuffer(texture._framebuffer);
  12230. }
  12231. texture.samples = samples;
  12232. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12234. this.bindUnboundFramebuffer(null);
  12235. return samples;
  12236. };
  12237. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12238. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12239. return 1;
  12240. }
  12241. if (textures[0].samples === samples) {
  12242. return samples;
  12243. }
  12244. var gl = this._gl;
  12245. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12246. // Dispose previous render buffers
  12247. if (textures[0]._depthStencilBuffer) {
  12248. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12249. textures[0]._depthStencilBuffer = null;
  12250. }
  12251. if (textures[0]._MSAAFramebuffer) {
  12252. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12253. textures[0]._MSAAFramebuffer = null;
  12254. }
  12255. for (var i = 0; i < textures.length; i++) {
  12256. if (textures[i]._MSAARenderBuffer) {
  12257. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12258. textures[i]._MSAARenderBuffer = null;
  12259. }
  12260. }
  12261. if (samples > 1) {
  12262. var framebuffer = gl.createFramebuffer();
  12263. if (!framebuffer) {
  12264. throw new Error("Unable to create multi sampled framebuffer");
  12265. }
  12266. this.bindUnboundFramebuffer(framebuffer);
  12267. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12268. var attachments = [];
  12269. for (var i = 0; i < textures.length; i++) {
  12270. var texture = textures[i];
  12271. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12272. var colorRenderbuffer = gl.createRenderbuffer();
  12273. if (!colorRenderbuffer) {
  12274. throw new Error("Unable to create multi sampled framebuffer");
  12275. }
  12276. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12277. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12278. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12279. texture._MSAAFramebuffer = framebuffer;
  12280. texture._MSAARenderBuffer = colorRenderbuffer;
  12281. texture.samples = samples;
  12282. texture._depthStencilBuffer = depthStencilBuffer;
  12283. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12284. attachments.push(attachment);
  12285. }
  12286. gl.drawBuffers(attachments);
  12287. }
  12288. else {
  12289. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12290. }
  12291. this.bindUnboundFramebuffer(null);
  12292. return samples;
  12293. };
  12294. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12295. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12296. };
  12297. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12298. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12299. };
  12300. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12301. var gl = this._gl;
  12302. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12303. var generateMipMaps = true;
  12304. var generateDepthBuffer = true;
  12305. var generateStencilBuffer = false;
  12306. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12307. if (options !== undefined) {
  12308. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12309. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12310. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12311. if (options.samplingMode !== undefined) {
  12312. samplingMode = options.samplingMode;
  12313. }
  12314. }
  12315. texture.isCube = true;
  12316. texture.generateMipMaps = generateMipMaps;
  12317. texture.samples = 1;
  12318. texture.samplingMode = samplingMode;
  12319. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12320. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12321. for (var face = 0; face < 6; face++) {
  12322. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12323. }
  12324. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12325. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12326. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12327. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12328. // Create the framebuffer
  12329. var framebuffer = gl.createFramebuffer();
  12330. this.bindUnboundFramebuffer(framebuffer);
  12331. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12332. // Mipmaps
  12333. if (texture.generateMipMaps) {
  12334. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12335. }
  12336. // Unbind
  12337. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12338. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12339. this.bindUnboundFramebuffer(null);
  12340. texture._framebuffer = framebuffer;
  12341. texture.width = size;
  12342. texture.height = size;
  12343. texture.isReady = true;
  12344. //this.resetTextureCache();
  12345. this._internalTexturesCache.push(texture);
  12346. return texture;
  12347. };
  12348. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12349. var _this = this;
  12350. if (onLoad === void 0) { onLoad = null; }
  12351. if (onError === void 0) { onError = null; }
  12352. if (forcedExtension === void 0) { forcedExtension = null; }
  12353. var callback = function (loadData) {
  12354. if (!loadData) {
  12355. if (onLoad) {
  12356. onLoad(null);
  12357. }
  12358. return;
  12359. }
  12360. var texture = loadData.texture;
  12361. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12362. texture._lodGenerationScale = scale;
  12363. texture._lodGenerationOffset = offset;
  12364. if (_this._caps.textureLOD) {
  12365. // Do not add extra process if texture lod is supported.
  12366. if (onLoad) {
  12367. onLoad(texture);
  12368. }
  12369. return;
  12370. }
  12371. var mipSlices = 3;
  12372. var gl = _this._gl;
  12373. var width = loadData.width;
  12374. if (!width) {
  12375. return;
  12376. }
  12377. var textures = [];
  12378. for (var i = 0; i < mipSlices; i++) {
  12379. //compute LOD from even spacing in smoothness (matching shader calculation)
  12380. var smoothness = i / (mipSlices - 1);
  12381. var roughness = 1 - smoothness;
  12382. var minLODIndex = offset; // roughness = 0
  12383. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12384. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12385. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12386. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12387. glTextureFromLod.isCube = true;
  12388. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12393. if (loadData.isDDS) {
  12394. var info = loadData.info;
  12395. var data = loadData.data;
  12396. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12397. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12398. }
  12399. else {
  12400. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12401. }
  12402. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12403. // Wrap in a base texture for easy binding.
  12404. var lodTexture = new BABYLON.BaseTexture(scene);
  12405. lodTexture.isCube = true;
  12406. lodTexture._texture = glTextureFromLod;
  12407. glTextureFromLod.isReady = true;
  12408. textures.push(lodTexture);
  12409. }
  12410. texture._lodTextureHigh = textures[2];
  12411. texture._lodTextureMid = textures[1];
  12412. texture._lodTextureLow = textures[0];
  12413. if (onLoad) {
  12414. onLoad(texture);
  12415. }
  12416. };
  12417. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12418. };
  12419. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12420. var _this = this;
  12421. if (onLoad === void 0) { onLoad = null; }
  12422. if (onError === void 0) { onError = null; }
  12423. if (forcedExtension === void 0) { forcedExtension = null; }
  12424. var gl = this._gl;
  12425. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12426. texture.isCube = true;
  12427. texture.url = rootUrl;
  12428. texture.generateMipMaps = !noMipmap;
  12429. if (!this._doNotHandleContextLost) {
  12430. texture._extension = forcedExtension;
  12431. texture._files = files;
  12432. }
  12433. var isKTX = false;
  12434. var isDDS = false;
  12435. var lastDot = rootUrl.lastIndexOf('.');
  12436. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12437. if (this._textureFormatInUse) {
  12438. extension = this._textureFormatInUse;
  12439. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12440. isKTX = true;
  12441. }
  12442. else {
  12443. isDDS = (extension === ".dds");
  12444. }
  12445. var onerror = function (request, exception) {
  12446. if (onError && request) {
  12447. onError(request.status + " " + request.statusText, exception);
  12448. }
  12449. };
  12450. if (isKTX) {
  12451. this._loadFile(rootUrl, function (data) {
  12452. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12453. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12454. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12455. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12456. ktx.uploadLevels(_this._gl, !noMipmap);
  12457. _this.setCubeMapTextureParams(gl, loadMipmap);
  12458. texture.width = ktx.pixelWidth;
  12459. texture.height = ktx.pixelHeight;
  12460. texture.isReady = true;
  12461. }, undefined, undefined, true, onerror);
  12462. }
  12463. else if (isDDS) {
  12464. if (files && files.length === 6) {
  12465. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12466. var info;
  12467. var loadMipmap = false;
  12468. var width = 0;
  12469. for (var index = 0; index < imgs.length; index++) {
  12470. var data = imgs[index];
  12471. info = BABYLON.DDSTools.GetDDSInfo(data);
  12472. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12473. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12474. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12475. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12476. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12477. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12478. }
  12479. texture.width = info.width;
  12480. texture.height = info.height;
  12481. texture.type = info.textureType;
  12482. width = info.width;
  12483. }
  12484. _this.setCubeMapTextureParams(gl, loadMipmap);
  12485. texture.isReady = true;
  12486. if (onLoad) {
  12487. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12488. }
  12489. }, files, onError);
  12490. }
  12491. else {
  12492. this._loadFile(rootUrl, function (data) {
  12493. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12494. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12495. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12496. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12497. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12498. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12499. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12500. }
  12501. _this.setCubeMapTextureParams(gl, loadMipmap);
  12502. texture.width = info.width;
  12503. texture.height = info.height;
  12504. texture.isReady = true;
  12505. texture.type = info.textureType;
  12506. if (onLoad) {
  12507. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12508. }
  12509. }, undefined, undefined, true, onerror);
  12510. }
  12511. }
  12512. else {
  12513. if (!files) {
  12514. throw new Error("Cannot load cubemap because files were not defined");
  12515. }
  12516. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12517. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12518. var height = width;
  12519. _this._prepareWorkingCanvas();
  12520. if (!_this._workingCanvas || !_this._workingContext) {
  12521. return;
  12522. }
  12523. _this._workingCanvas.width = width;
  12524. _this._workingCanvas.height = height;
  12525. var faces = [
  12526. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12527. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12528. ];
  12529. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12530. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12531. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12532. for (var index = 0; index < faces.length; index++) {
  12533. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12534. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12535. }
  12536. if (!noMipmap) {
  12537. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12538. }
  12539. _this.setCubeMapTextureParams(gl, !noMipmap);
  12540. texture.width = width;
  12541. texture.height = height;
  12542. texture.isReady = true;
  12543. if (format) {
  12544. texture.format = format;
  12545. }
  12546. texture.onLoadedObservable.notifyObservers(texture);
  12547. texture.onLoadedObservable.clear();
  12548. if (onLoad) {
  12549. onLoad();
  12550. }
  12551. }, files, onError);
  12552. }
  12553. this._internalTexturesCache.push(texture);
  12554. return texture;
  12555. };
  12556. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12561. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12562. // this.resetTextureCache();
  12563. };
  12564. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12565. if (compression === void 0) { compression = null; }
  12566. if (level === void 0) { level = 0; }
  12567. texture._bufferViewArray = data;
  12568. texture.format = format;
  12569. texture.type = type;
  12570. texture.invertY = invertY;
  12571. texture._compression = compression;
  12572. var gl = this._gl;
  12573. var textureType = this._getWebGLTextureType(type);
  12574. var internalFormat = this._getInternalFormat(format);
  12575. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12576. var needConversion = false;
  12577. if (internalFormat === gl.RGB) {
  12578. internalFormat = gl.RGBA;
  12579. needConversion = true;
  12580. }
  12581. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12582. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12583. if (texture.width % 4 !== 0) {
  12584. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12585. }
  12586. // Data are known to be in +X +Y +Z -X -Y -Z
  12587. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12588. var faceData = data[faceIndex];
  12589. if (compression) {
  12590. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12591. }
  12592. else {
  12593. if (needConversion) {
  12594. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12595. }
  12596. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12597. }
  12598. }
  12599. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12600. if (isPot && texture.generateMipMaps && level === 0) {
  12601. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12602. }
  12603. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12604. // this.resetTextureCache();
  12605. texture.isReady = true;
  12606. };
  12607. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12608. if (compression === void 0) { compression = null; }
  12609. var gl = this._gl;
  12610. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12611. texture.isCube = true;
  12612. texture.generateMipMaps = generateMipMaps;
  12613. texture.format = format;
  12614. texture.type = type;
  12615. if (!this._doNotHandleContextLost) {
  12616. texture._bufferViewArray = data;
  12617. }
  12618. var textureType = this._getWebGLTextureType(type);
  12619. var internalFormat = this._getInternalFormat(format);
  12620. if (internalFormat === gl.RGB) {
  12621. internalFormat = gl.RGBA;
  12622. }
  12623. var width = size;
  12624. var height = width;
  12625. texture.width = width;
  12626. texture.height = height;
  12627. // Double check on POT to generate Mips.
  12628. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12629. if (!isPot) {
  12630. generateMipMaps = false;
  12631. }
  12632. // Upload data if needed. The texture won't be ready until then.
  12633. if (data) {
  12634. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12635. }
  12636. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12637. // Filters
  12638. if (data && generateMipMaps) {
  12639. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12640. }
  12641. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12644. }
  12645. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12648. }
  12649. else {
  12650. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12651. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12653. }
  12654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12656. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12657. return texture;
  12658. };
  12659. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12660. var _this = this;
  12661. if (onLoad === void 0) { onLoad = null; }
  12662. if (onError === void 0) { onError = null; }
  12663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12664. if (invertY === void 0) { invertY = false; }
  12665. var gl = this._gl;
  12666. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12667. scene._addPendingData(texture);
  12668. texture.url = url;
  12669. this._internalTexturesCache.push(texture);
  12670. var onerror = function (request, exception) {
  12671. scene._removePendingData(texture);
  12672. if (onError && request) {
  12673. onError(request.status + " " + request.statusText, exception);
  12674. }
  12675. };
  12676. var internalCallback = function (data) {
  12677. var width = texture.width;
  12678. var faceDataArrays = callback(data);
  12679. if (!faceDataArrays) {
  12680. return;
  12681. }
  12682. if (mipmmapGenerator) {
  12683. var textureType = _this._getWebGLTextureType(type);
  12684. var internalFormat = _this._getInternalFormat(format);
  12685. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12686. var needConversion = false;
  12687. if (internalFormat === gl.RGB) {
  12688. internalFormat = gl.RGBA;
  12689. needConversion = true;
  12690. }
  12691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12693. var mipData = mipmmapGenerator(faceDataArrays);
  12694. for (var level = 0; level < mipData.length; level++) {
  12695. var mipSize = width >> level;
  12696. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12697. var mipFaceData = mipData[level][faceIndex];
  12698. if (needConversion) {
  12699. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12700. }
  12701. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12702. }
  12703. }
  12704. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12705. }
  12706. else {
  12707. texture.generateMipMaps = !noMipmap;
  12708. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12709. }
  12710. texture.isReady = true;
  12711. // this.resetTextureCache();
  12712. scene._removePendingData(texture);
  12713. if (onLoad) {
  12714. onLoad();
  12715. }
  12716. };
  12717. this._loadFile(url, function (data) {
  12718. internalCallback(data);
  12719. }, undefined, scene.database, true, onerror);
  12720. return texture;
  12721. };
  12722. ;
  12723. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12724. if (compression === void 0) { compression = null; }
  12725. var internalFormat = this._getInternalFormat(format);
  12726. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12727. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12728. if (!this._doNotHandleContextLost) {
  12729. texture._bufferView = data;
  12730. texture.format = format;
  12731. texture.invertY = invertY;
  12732. texture._compression = compression;
  12733. }
  12734. if (texture.width % 4 !== 0) {
  12735. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12736. }
  12737. if (compression && data) {
  12738. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12739. }
  12740. else {
  12741. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12742. }
  12743. if (texture.generateMipMaps) {
  12744. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12745. }
  12746. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12747. // this.resetTextureCache();
  12748. texture.isReady = true;
  12749. };
  12750. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12751. if (compression === void 0) { compression = null; }
  12752. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12753. texture.baseWidth = width;
  12754. texture.baseHeight = height;
  12755. texture.baseDepth = depth;
  12756. texture.width = width;
  12757. texture.height = height;
  12758. texture.depth = depth;
  12759. texture.format = format;
  12760. texture.generateMipMaps = generateMipMaps;
  12761. texture.samplingMode = samplingMode;
  12762. texture.is3D = true;
  12763. if (!this._doNotHandleContextLost) {
  12764. texture._bufferView = data;
  12765. }
  12766. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12767. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12768. // Filters
  12769. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12770. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12771. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12772. if (generateMipMaps) {
  12773. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12774. }
  12775. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12776. this._internalTexturesCache.push(texture);
  12777. return texture;
  12778. };
  12779. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12780. var gl = this._gl;
  12781. if (!gl) {
  12782. return;
  12783. }
  12784. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12787. if (!noMipmap && !isCompressed) {
  12788. gl.generateMipmap(gl.TEXTURE_2D);
  12789. }
  12790. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12791. // this.resetTextureCache();
  12792. if (scene) {
  12793. scene._removePendingData(texture);
  12794. }
  12795. texture.onLoadedObservable.notifyObservers(texture);
  12796. texture.onLoadedObservable.clear();
  12797. };
  12798. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12799. var _this = this;
  12800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12801. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12802. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12803. var gl = this._gl;
  12804. if (!gl) {
  12805. return;
  12806. }
  12807. if (!texture._webGLTexture) {
  12808. // this.resetTextureCache();
  12809. if (scene) {
  12810. scene._removePendingData(texture);
  12811. }
  12812. return;
  12813. }
  12814. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12815. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12816. texture.baseWidth = width;
  12817. texture.baseHeight = height;
  12818. texture.width = potWidth;
  12819. texture.height = potHeight;
  12820. texture.isReady = true;
  12821. if (processFunction(potWidth, potHeight, function () {
  12822. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12823. })) {
  12824. // Returning as texture needs extra async steps
  12825. return;
  12826. }
  12827. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12828. };
  12829. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12830. // Create new RGBA data container.
  12831. var rgbaData;
  12832. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12833. rgbaData = new Float32Array(width * height * 4);
  12834. }
  12835. else {
  12836. rgbaData = new Uint32Array(width * height * 4);
  12837. }
  12838. // Convert each pixel.
  12839. for (var x = 0; x < width; x++) {
  12840. for (var y = 0; y < height; y++) {
  12841. var index = (y * width + x) * 3;
  12842. var newIndex = (y * width + x) * 4;
  12843. // Map Old Value to new value.
  12844. rgbaData[newIndex + 0] = rgbData[index + 0];
  12845. rgbaData[newIndex + 1] = rgbData[index + 1];
  12846. rgbaData[newIndex + 2] = rgbData[index + 2];
  12847. // Add fully opaque alpha channel.
  12848. rgbaData[newIndex + 3] = 1;
  12849. }
  12850. }
  12851. return rgbaData;
  12852. };
  12853. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12854. var gl = this._gl;
  12855. if (texture._framebuffer) {
  12856. gl.deleteFramebuffer(texture._framebuffer);
  12857. texture._framebuffer = null;
  12858. }
  12859. if (texture._depthStencilBuffer) {
  12860. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12861. texture._depthStencilBuffer = null;
  12862. }
  12863. if (texture._MSAAFramebuffer) {
  12864. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12865. texture._MSAAFramebuffer = null;
  12866. }
  12867. if (texture._MSAARenderBuffer) {
  12868. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12869. texture._MSAARenderBuffer = null;
  12870. }
  12871. };
  12872. Engine.prototype._releaseTexture = function (texture) {
  12873. var gl = this._gl;
  12874. this._releaseFramebufferObjects(texture);
  12875. gl.deleteTexture(texture._webGLTexture);
  12876. // Unbind channels
  12877. this.unbindAllTextures();
  12878. var index = this._internalTexturesCache.indexOf(texture);
  12879. if (index !== -1) {
  12880. this._internalTexturesCache.splice(index, 1);
  12881. }
  12882. // Integrated fixed lod samplers.
  12883. if (texture._lodTextureHigh) {
  12884. texture._lodTextureHigh.dispose();
  12885. }
  12886. if (texture._lodTextureMid) {
  12887. texture._lodTextureMid.dispose();
  12888. }
  12889. if (texture._lodTextureLow) {
  12890. texture._lodTextureLow.dispose();
  12891. }
  12892. };
  12893. Engine.prototype.setProgram = function (program) {
  12894. if (this._currentProgram !== program) {
  12895. this._gl.useProgram(program);
  12896. this._currentProgram = program;
  12897. }
  12898. };
  12899. Engine.prototype.bindSamplers = function (effect) {
  12900. this.setProgram(effect.getProgram());
  12901. var samplers = effect.getSamplers();
  12902. for (var index = 0; index < samplers.length; index++) {
  12903. var uniform = effect.getUniform(samplers[index]);
  12904. if (uniform) {
  12905. this._boundUniforms[index] = uniform;
  12906. }
  12907. }
  12908. this._currentEffect = null;
  12909. };
  12910. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12911. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  12912. return;
  12913. }
  12914. // Remove
  12915. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12916. // Bind last to it
  12917. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  12918. // Bind to dummy
  12919. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  12920. };
  12921. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12922. if (!internalTexture) {
  12923. return -1;
  12924. }
  12925. internalTexture._initialSlot = channel;
  12926. if (this.disableTextureBindingOptimization) {
  12927. if (channel !== internalTexture._designatedSlot) {
  12928. this._textureCollisions.addCount(1, false);
  12929. }
  12930. }
  12931. else {
  12932. if (channel !== internalTexture._designatedSlot) {
  12933. if (internalTexture._designatedSlot > -1) {
  12934. return internalTexture._designatedSlot;
  12935. }
  12936. else {
  12937. // No slot for this texture, let's pick a new one (if we find a free slot)
  12938. if (this._nextFreeTextureSlots.length) {
  12939. return this._nextFreeTextureSlots[0];
  12940. }
  12941. // We need to recycle the oldest bound texture, sorry.
  12942. this._textureCollisions.addCount(1, false);
  12943. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  12944. }
  12945. }
  12946. }
  12947. return channel;
  12948. };
  12949. Engine.prototype._linkTrackers = function (previous, next) {
  12950. previous.next = next;
  12951. next.previous = previous;
  12952. };
  12953. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12954. var currentSlot = internalTexture._designatedSlot;
  12955. if (currentSlot === -1) {
  12956. return -1;
  12957. }
  12958. internalTexture._designatedSlot = -1;
  12959. // Remove from bound list
  12960. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12961. // Free the slot
  12962. this._boundTexturesCache[currentSlot] = null;
  12963. this._nextFreeTextureSlots.push(currentSlot);
  12964. return currentSlot;
  12965. };
  12966. Engine.prototype._activateCurrentTexture = function () {
  12967. if (this._currentTextureChannel !== this._activeChannel) {
  12968. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12969. this._currentTextureChannel = this._activeChannel;
  12970. }
  12971. };
  12972. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12973. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12974. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12975. this._activeChannel = texture._designatedSlot;
  12976. }
  12977. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12978. var isTextureForRendering = texture && texture._initialSlot > -1;
  12979. if (currentTextureBound !== texture) {
  12980. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12981. this._removeDesignatedSlot(currentTextureBound);
  12982. }
  12983. this._activateCurrentTexture();
  12984. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12985. this._boundTexturesCache[this._activeChannel] = texture;
  12986. if (texture) {
  12987. if (!this.disableTextureBindingOptimization) {
  12988. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12989. if (slotIndex > -1) {
  12990. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12991. }
  12992. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  12993. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  12994. }
  12995. texture._designatedSlot = this._activeChannel;
  12996. }
  12997. }
  12998. else if (forTextureDataUpdate) {
  12999. this._activateCurrentTexture();
  13000. }
  13001. if (isTextureForRendering && !forTextureDataUpdate) {
  13002. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13003. }
  13004. };
  13005. Engine.prototype._bindTexture = function (channel, texture) {
  13006. if (channel < 0) {
  13007. return;
  13008. }
  13009. if (texture) {
  13010. channel = this._getCorrectTextureChannel(channel, texture);
  13011. }
  13012. this._activeChannel = channel;
  13013. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13014. };
  13015. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13016. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13017. };
  13018. Engine.prototype.unbindAllTextures = function () {
  13019. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13020. this._activeChannel = channel;
  13021. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13022. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13023. if (this.webGLVersion > 1) {
  13024. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13025. }
  13026. }
  13027. };
  13028. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13029. if (channel < 0) {
  13030. return;
  13031. }
  13032. if (uniform) {
  13033. this._boundUniforms[channel] = uniform;
  13034. }
  13035. this._setTexture(channel, texture);
  13036. };
  13037. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13038. var uniform = this._boundUniforms[sourceSlot];
  13039. if (uniform._currentState === destination) {
  13040. return;
  13041. }
  13042. this._gl.uniform1i(uniform, destination);
  13043. uniform._currentState = destination;
  13044. };
  13045. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13046. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13047. // Not ready?
  13048. if (!texture) {
  13049. if (this._boundTexturesCache[channel] != null) {
  13050. this._activeChannel = channel;
  13051. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13052. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13053. if (this.webGLVersion > 1) {
  13054. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13055. }
  13056. }
  13057. return false;
  13058. }
  13059. // Video
  13060. if (texture.video) {
  13061. this._activeChannel = channel;
  13062. texture.update();
  13063. }
  13064. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13065. texture.delayLoad();
  13066. return false;
  13067. }
  13068. var internalTexture;
  13069. if (texture.isReady()) {
  13070. internalTexture = texture.getInternalTexture();
  13071. }
  13072. else if (texture.isCube) {
  13073. internalTexture = this.emptyCubeTexture;
  13074. }
  13075. else if (texture.is3D) {
  13076. internalTexture = this.emptyTexture3D;
  13077. }
  13078. else {
  13079. internalTexture = this.emptyTexture;
  13080. }
  13081. if (!isPartOfTextureArray) {
  13082. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13083. }
  13084. if (this._boundTexturesCache[channel] === internalTexture) {
  13085. this._moveBoundTextureOnTop(internalTexture);
  13086. if (!isPartOfTextureArray) {
  13087. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13088. }
  13089. return false;
  13090. }
  13091. this._activeChannel = channel;
  13092. if (internalTexture && internalTexture.is3D) {
  13093. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13094. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13095. internalTexture._cachedWrapU = texture.wrapU;
  13096. switch (texture.wrapU) {
  13097. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13098. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13099. break;
  13100. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13101. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13102. break;
  13103. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13104. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13105. break;
  13106. }
  13107. }
  13108. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13109. internalTexture._cachedWrapV = texture.wrapV;
  13110. switch (texture.wrapV) {
  13111. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13112. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13113. break;
  13114. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13115. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13116. break;
  13117. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13118. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13119. break;
  13120. }
  13121. }
  13122. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13123. internalTexture._cachedWrapR = texture.wrapR;
  13124. switch (texture.wrapV) {
  13125. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13126. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13127. break;
  13128. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13129. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13130. break;
  13131. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13132. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13133. break;
  13134. }
  13135. }
  13136. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13137. }
  13138. else if (internalTexture && internalTexture.isCube) {
  13139. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13140. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13141. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13142. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13143. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13144. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13145. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13146. }
  13147. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13148. }
  13149. else {
  13150. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13151. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13152. internalTexture._cachedWrapU = texture.wrapU;
  13153. switch (texture.wrapU) {
  13154. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13155. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13156. break;
  13157. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13158. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13159. break;
  13160. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13161. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13162. break;
  13163. }
  13164. }
  13165. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13166. internalTexture._cachedWrapV = texture.wrapV;
  13167. switch (texture.wrapV) {
  13168. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13169. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13170. break;
  13171. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13172. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13173. break;
  13174. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13175. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13176. break;
  13177. }
  13178. }
  13179. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13180. }
  13181. return true;
  13182. };
  13183. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13184. if (channel < 0 || !uniform) {
  13185. return;
  13186. }
  13187. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13188. this._textureUnits = new Int32Array(textures.length);
  13189. }
  13190. for (var i = 0; i < textures.length; i++) {
  13191. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13192. }
  13193. this._gl.uniform1iv(uniform, this._textureUnits);
  13194. for (var index = 0; index < textures.length; index++) {
  13195. this._setTexture(this._textureUnits[index], textures[index], true);
  13196. }
  13197. };
  13198. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13199. var internalTexture = texture.getInternalTexture();
  13200. if (!internalTexture) {
  13201. return;
  13202. }
  13203. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13204. var value = texture.anisotropicFilteringLevel;
  13205. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13206. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13207. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13208. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13209. }
  13210. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13211. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13212. internalTexture._cachedAnisotropicFilteringLevel = value;
  13213. }
  13214. };
  13215. Engine.prototype.readPixels = function (x, y, width, height) {
  13216. var data = new Uint8Array(height * width * 4);
  13217. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13218. return data;
  13219. };
  13220. /**
  13221. * Add an externaly attached data from its key.
  13222. * This method call will fail and return false, if such key already exists.
  13223. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13224. * @param key the unique key that identifies the data
  13225. * @param data the data object to associate to the key for this Engine instance
  13226. * @return true if no such key were already present and the data was added successfully, false otherwise
  13227. */
  13228. Engine.prototype.addExternalData = function (key, data) {
  13229. if (!this._externalData) {
  13230. this._externalData = new BABYLON.StringDictionary();
  13231. }
  13232. return this._externalData.add(key, data);
  13233. };
  13234. /**
  13235. * Get an externaly attached data from its key
  13236. * @param key the unique key that identifies the data
  13237. * @return the associated data, if present (can be null), or undefined if not present
  13238. */
  13239. Engine.prototype.getExternalData = function (key) {
  13240. if (!this._externalData) {
  13241. this._externalData = new BABYLON.StringDictionary();
  13242. }
  13243. return this._externalData.get(key);
  13244. };
  13245. /**
  13246. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13247. * @param key the unique key that identifies the data
  13248. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13249. * @return the associated data, can be null if the factory returned null.
  13250. */
  13251. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13252. if (!this._externalData) {
  13253. this._externalData = new BABYLON.StringDictionary();
  13254. }
  13255. return this._externalData.getOrAddWithFactory(key, factory);
  13256. };
  13257. /**
  13258. * Remove an externaly attached data from the Engine instance
  13259. * @param key the unique key that identifies the data
  13260. * @return true if the data was successfully removed, false if it doesn't exist
  13261. */
  13262. Engine.prototype.removeExternalData = function (key) {
  13263. if (!this._externalData) {
  13264. this._externalData = new BABYLON.StringDictionary();
  13265. }
  13266. return this._externalData.remove(key);
  13267. };
  13268. Engine.prototype.unbindAllAttributes = function () {
  13269. if (this._mustWipeVertexAttributes) {
  13270. this._mustWipeVertexAttributes = false;
  13271. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13272. this._gl.disableVertexAttribArray(i);
  13273. this._vertexAttribArraysEnabled[i] = false;
  13274. this._currentBufferPointers[i].active = false;
  13275. }
  13276. return;
  13277. }
  13278. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13279. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13280. continue;
  13281. }
  13282. this._gl.disableVertexAttribArray(i);
  13283. this._vertexAttribArraysEnabled[i] = false;
  13284. this._currentBufferPointers[i].active = false;
  13285. }
  13286. };
  13287. Engine.prototype.releaseEffects = function () {
  13288. for (var name in this._compiledEffects) {
  13289. this._deleteProgram(this._compiledEffects[name]._program);
  13290. }
  13291. this._compiledEffects = {};
  13292. };
  13293. // Dispose
  13294. Engine.prototype.dispose = function () {
  13295. this.hideLoadingUI();
  13296. this.stopRenderLoop();
  13297. // Release postProcesses
  13298. while (this.postProcesses.length) {
  13299. this.postProcesses[0].dispose();
  13300. }
  13301. // Empty texture
  13302. if (this._emptyTexture) {
  13303. this._releaseTexture(this._emptyTexture);
  13304. this._emptyTexture = null;
  13305. }
  13306. if (this._emptyCubeTexture) {
  13307. this._releaseTexture(this._emptyCubeTexture);
  13308. this._emptyCubeTexture = null;
  13309. }
  13310. // Rescale PP
  13311. if (this._rescalePostProcess) {
  13312. this._rescalePostProcess.dispose();
  13313. }
  13314. // Release scenes
  13315. while (this.scenes.length) {
  13316. this.scenes[0].dispose();
  13317. }
  13318. // Release audio engine
  13319. if (Engine.audioEngine) {
  13320. Engine.audioEngine.dispose();
  13321. }
  13322. // Release effects
  13323. this.releaseEffects();
  13324. // Unbind
  13325. this.unbindAllAttributes();
  13326. if (this._dummyFramebuffer) {
  13327. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13328. }
  13329. //WebVR
  13330. this.disableVR();
  13331. // Events
  13332. if (BABYLON.Tools.IsWindowObjectExist()) {
  13333. window.removeEventListener("blur", this._onBlur);
  13334. window.removeEventListener("focus", this._onFocus);
  13335. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13336. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13337. if (this._renderingCanvas) {
  13338. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13339. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13340. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13341. if (!this._doNotHandleContextLost) {
  13342. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13343. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13344. }
  13345. }
  13346. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13347. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13348. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13349. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13350. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13351. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13352. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13353. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13354. if (this._onVrDisplayConnect) {
  13355. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13356. if (this._onVrDisplayDisconnect) {
  13357. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13358. }
  13359. if (this._onVrDisplayPresentChange) {
  13360. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13361. }
  13362. this._onVrDisplayConnect = null;
  13363. this._onVrDisplayDisconnect = null;
  13364. }
  13365. }
  13366. // Remove from Instances
  13367. var index = Engine.Instances.indexOf(this);
  13368. if (index >= 0) {
  13369. Engine.Instances.splice(index, 1);
  13370. }
  13371. this._workingCanvas = null;
  13372. this._workingContext = null;
  13373. this._currentBufferPointers = [];
  13374. this._renderingCanvas = null;
  13375. this._currentProgram = null;
  13376. this.onResizeObservable.clear();
  13377. this.onCanvasBlurObservable.clear();
  13378. this.onCanvasFocusObservable.clear();
  13379. this.onCanvasPointerOutObservable.clear();
  13380. this.onBeginFrameObservable.clear();
  13381. this.onEndFrameObservable.clear();
  13382. BABYLON.Effect.ResetCache();
  13383. // Abort active requests
  13384. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13385. var request = _a[_i];
  13386. request.abort();
  13387. }
  13388. };
  13389. // Loading screen
  13390. Engine.prototype.displayLoadingUI = function () {
  13391. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13392. return;
  13393. }
  13394. var loadingScreen = this.loadingScreen;
  13395. if (loadingScreen) {
  13396. loadingScreen.displayLoadingUI();
  13397. }
  13398. };
  13399. Engine.prototype.hideLoadingUI = function () {
  13400. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13401. return;
  13402. }
  13403. var loadingScreen = this.loadingScreen;
  13404. if (loadingScreen) {
  13405. loadingScreen.hideLoadingUI();
  13406. }
  13407. };
  13408. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13409. get: function () {
  13410. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13411. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13412. return this._loadingScreen;
  13413. },
  13414. set: function (loadingScreen) {
  13415. this._loadingScreen = loadingScreen;
  13416. },
  13417. enumerable: true,
  13418. configurable: true
  13419. });
  13420. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13421. set: function (text) {
  13422. this.loadingScreen.loadingUIText = text;
  13423. },
  13424. enumerable: true,
  13425. configurable: true
  13426. });
  13427. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13428. set: function (color) {
  13429. this.loadingScreen.loadingUIBackgroundColor = color;
  13430. },
  13431. enumerable: true,
  13432. configurable: true
  13433. });
  13434. Engine.prototype.attachContextLostEvent = function (callback) {
  13435. if (this._renderingCanvas) {
  13436. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13437. }
  13438. };
  13439. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13440. if (this._renderingCanvas) {
  13441. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13442. }
  13443. };
  13444. Engine.prototype.getVertexShaderSource = function (program) {
  13445. var shaders = this._gl.getAttachedShaders(program);
  13446. if (!shaders) {
  13447. return null;
  13448. }
  13449. return this._gl.getShaderSource(shaders[0]);
  13450. };
  13451. Engine.prototype.getFragmentShaderSource = function (program) {
  13452. var shaders = this._gl.getAttachedShaders(program);
  13453. if (!shaders) {
  13454. return null;
  13455. }
  13456. return this._gl.getShaderSource(shaders[1]);
  13457. };
  13458. Engine.prototype.getError = function () {
  13459. return this._gl.getError();
  13460. };
  13461. // FPS
  13462. Engine.prototype.getFps = function () {
  13463. return this._fps;
  13464. };
  13465. Engine.prototype.getDeltaTime = function () {
  13466. return this._deltaTime;
  13467. };
  13468. Engine.prototype._measureFps = function () {
  13469. this._performanceMonitor.sampleFrame();
  13470. this._fps = this._performanceMonitor.averageFPS;
  13471. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13472. };
  13473. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13474. if (faceIndex === void 0) { faceIndex = -1; }
  13475. var gl = this._gl;
  13476. if (!this._dummyFramebuffer) {
  13477. var dummy = gl.createFramebuffer();
  13478. if (!dummy) {
  13479. throw new Error("Unable to create dummy framebuffer");
  13480. }
  13481. this._dummyFramebuffer = dummy;
  13482. }
  13483. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13484. if (faceIndex > -1) {
  13485. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13486. }
  13487. else {
  13488. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13489. }
  13490. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13491. var buffer;
  13492. switch (readType) {
  13493. case gl.UNSIGNED_BYTE:
  13494. buffer = new Uint8Array(4 * width * height);
  13495. readType = gl.UNSIGNED_BYTE;
  13496. break;
  13497. default:
  13498. buffer = new Float32Array(4 * width * height);
  13499. readType = gl.FLOAT;
  13500. break;
  13501. }
  13502. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13503. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13504. return buffer;
  13505. };
  13506. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13507. if (this._webGLVersion > 1) {
  13508. return this._caps.colorBufferFloat;
  13509. }
  13510. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13511. };
  13512. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13513. if (this._webGLVersion > 1) {
  13514. return this._caps.colorBufferFloat;
  13515. }
  13516. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13517. };
  13518. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13519. Engine.prototype._canRenderToFramebuffer = function (type) {
  13520. var gl = this._gl;
  13521. //clear existing errors
  13522. while (gl.getError() !== gl.NO_ERROR) { }
  13523. var successful = true;
  13524. var texture = gl.createTexture();
  13525. gl.bindTexture(gl.TEXTURE_2D, texture);
  13526. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13528. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13529. var fb = gl.createFramebuffer();
  13530. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13531. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13532. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13533. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13534. successful = successful && (gl.getError() === gl.NO_ERROR);
  13535. //try render by clearing frame buffer's color buffer
  13536. if (successful) {
  13537. gl.clear(gl.COLOR_BUFFER_BIT);
  13538. successful = successful && (gl.getError() === gl.NO_ERROR);
  13539. }
  13540. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13541. if (successful) {
  13542. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13543. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13544. var readFormat = gl.RGBA;
  13545. var readType = gl.UNSIGNED_BYTE;
  13546. var buffer = new Uint8Array(4);
  13547. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13548. successful = successful && (gl.getError() === gl.NO_ERROR);
  13549. }
  13550. //clean up
  13551. gl.deleteTexture(texture);
  13552. gl.deleteFramebuffer(fb);
  13553. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13554. //clear accumulated errors
  13555. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13556. return successful;
  13557. };
  13558. Engine.prototype._getWebGLTextureType = function (type) {
  13559. if (type === Engine.TEXTURETYPE_FLOAT) {
  13560. return this._gl.FLOAT;
  13561. }
  13562. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13563. // Add Half Float Constant.
  13564. return this._gl.HALF_FLOAT_OES;
  13565. }
  13566. return this._gl.UNSIGNED_BYTE;
  13567. };
  13568. ;
  13569. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13570. if (this._webGLVersion === 1) {
  13571. return this._gl.RGBA;
  13572. }
  13573. if (type === Engine.TEXTURETYPE_FLOAT) {
  13574. return this._gl.RGBA32F;
  13575. }
  13576. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13577. return this._gl.RGBA16F;
  13578. }
  13579. return this._gl.RGBA;
  13580. };
  13581. ;
  13582. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13583. if (type === Engine.TEXTURETYPE_FLOAT) {
  13584. return this._gl.RGBA32F;
  13585. }
  13586. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13587. return this._gl.RGBA16F;
  13588. }
  13589. return this._gl.RGBA8;
  13590. };
  13591. ;
  13592. Engine.prototype.createQuery = function () {
  13593. return this._gl.createQuery();
  13594. };
  13595. Engine.prototype.deleteQuery = function (query) {
  13596. this._gl.deleteQuery(query);
  13597. return this;
  13598. };
  13599. Engine.prototype.isQueryResultAvailable = function (query) {
  13600. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13601. };
  13602. Engine.prototype.getQueryResult = function (query) {
  13603. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13604. };
  13605. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13606. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13607. this._gl.beginQuery(glAlgorithm, query);
  13608. return this;
  13609. };
  13610. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13611. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13612. this._gl.endQuery(glAlgorithm);
  13613. return this;
  13614. };
  13615. /* Time queries */
  13616. Engine.prototype._createTimeQuery = function () {
  13617. var timerQuery = this._caps.timerQuery;
  13618. if (timerQuery.createQueryEXT) {
  13619. return timerQuery.createQueryEXT();
  13620. }
  13621. return this.createQuery();
  13622. };
  13623. Engine.prototype._deleteTimeQuery = function (query) {
  13624. var timerQuery = this._caps.timerQuery;
  13625. if (timerQuery.deleteQueryEXT) {
  13626. timerQuery.deleteQueryEXT(query);
  13627. return;
  13628. }
  13629. this.deleteQuery(query);
  13630. };
  13631. Engine.prototype._getTimeQueryResult = function (query) {
  13632. var timerQuery = this._caps.timerQuery;
  13633. if (timerQuery.getQueryObjectEXT) {
  13634. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13635. }
  13636. return this.getQueryResult(query);
  13637. };
  13638. Engine.prototype._getTimeQueryAvailability = function (query) {
  13639. var timerQuery = this._caps.timerQuery;
  13640. if (timerQuery.getQueryObjectEXT) {
  13641. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13642. }
  13643. return this.isQueryResultAvailable(query);
  13644. };
  13645. Engine.prototype.startTimeQuery = function () {
  13646. var timerQuery = this._caps.timerQuery;
  13647. if (!timerQuery) {
  13648. return null;
  13649. }
  13650. var token = new BABYLON._TimeToken();
  13651. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13652. if (this._caps.canUseTimestampForTimerQuery) {
  13653. token._startTimeQuery = this._createTimeQuery();
  13654. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13655. }
  13656. else {
  13657. if (this._currentNonTimestampToken) {
  13658. return this._currentNonTimestampToken;
  13659. }
  13660. token._timeElapsedQuery = this._createTimeQuery();
  13661. if (timerQuery.beginQueryEXT) {
  13662. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13663. }
  13664. else {
  13665. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13666. }
  13667. this._currentNonTimestampToken = token;
  13668. }
  13669. return token;
  13670. };
  13671. Engine.prototype.endTimeQuery = function (token) {
  13672. var timerQuery = this._caps.timerQuery;
  13673. if (!timerQuery || !token) {
  13674. return -1;
  13675. }
  13676. if (this._caps.canUseTimestampForTimerQuery) {
  13677. if (!token._startTimeQuery) {
  13678. return -1;
  13679. }
  13680. if (!token._endTimeQuery) {
  13681. token._endTimeQuery = this._createTimeQuery();
  13682. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13683. }
  13684. }
  13685. else if (!token._timeElapsedQueryEnded) {
  13686. if (!token._timeElapsedQuery) {
  13687. return -1;
  13688. }
  13689. if (timerQuery.endQueryEXT) {
  13690. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13691. }
  13692. else {
  13693. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13694. }
  13695. token._timeElapsedQueryEnded = true;
  13696. }
  13697. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13698. var available = false;
  13699. if (token._endTimeQuery) {
  13700. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13701. }
  13702. else if (token._timeElapsedQuery) {
  13703. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13704. }
  13705. if (available && !disjoint) {
  13706. var result = 0;
  13707. if (this._caps.canUseTimestampForTimerQuery) {
  13708. if (!token._startTimeQuery || !token._endTimeQuery) {
  13709. return -1;
  13710. }
  13711. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13712. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13713. result = timeEnd - timeStart;
  13714. this._deleteTimeQuery(token._startTimeQuery);
  13715. this._deleteTimeQuery(token._endTimeQuery);
  13716. token._startTimeQuery = null;
  13717. token._endTimeQuery = null;
  13718. }
  13719. else {
  13720. if (!token._timeElapsedQuery) {
  13721. return -1;
  13722. }
  13723. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13724. this._deleteTimeQuery(token._timeElapsedQuery);
  13725. token._timeElapsedQuery = null;
  13726. token._timeElapsedQueryEnded = false;
  13727. this._currentNonTimestampToken = null;
  13728. }
  13729. return result;
  13730. }
  13731. return -1;
  13732. };
  13733. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13734. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13735. };
  13736. // Transform feedback
  13737. Engine.prototype.createTransformFeedback = function () {
  13738. return this._gl.createTransformFeedback();
  13739. };
  13740. Engine.prototype.deleteTransformFeedback = function (value) {
  13741. this._gl.deleteTransformFeedback(value);
  13742. };
  13743. Engine.prototype.bindTransformFeedback = function (value) {
  13744. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13745. };
  13746. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13747. if (usePoints === void 0) { usePoints = true; }
  13748. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13749. };
  13750. Engine.prototype.endTransformFeedback = function () {
  13751. this._gl.endTransformFeedback();
  13752. };
  13753. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13754. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13755. };
  13756. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13757. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13758. };
  13759. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13760. var _this = this;
  13761. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13762. this._activeRequests.push(request);
  13763. request.onCompleteObservable.add(function (request) {
  13764. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13765. });
  13766. return request;
  13767. };
  13768. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13769. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13770. var onload = function (data) {
  13771. loadedFiles[index] = data;
  13772. loadedFiles._internalCount++;
  13773. if (loadedFiles._internalCount === 6) {
  13774. onfinish(loadedFiles);
  13775. }
  13776. };
  13777. var onerror = function (request, exception) {
  13778. if (onErrorCallBack && request) {
  13779. onErrorCallBack(request.status + " " + request.statusText, exception);
  13780. }
  13781. };
  13782. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13783. };
  13784. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13785. if (onError === void 0) { onError = null; }
  13786. var loadedFiles = [];
  13787. loadedFiles._internalCount = 0;
  13788. for (var index = 0; index < 6; index++) {
  13789. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13790. }
  13791. };
  13792. // Statics
  13793. Engine.isSupported = function () {
  13794. try {
  13795. var tempcanvas = document.createElement("canvas");
  13796. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13797. return gl != null && !!window.WebGLRenderingContext;
  13798. }
  13799. catch (e) {
  13800. return false;
  13801. }
  13802. };
  13803. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13804. Engine.ExceptionList = [
  13805. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13806. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13807. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13808. ];
  13809. Engine.Instances = new Array();
  13810. // Const statics
  13811. Engine._ALPHA_DISABLE = 0;
  13812. Engine._ALPHA_ADD = 1;
  13813. Engine._ALPHA_COMBINE = 2;
  13814. Engine._ALPHA_SUBTRACT = 3;
  13815. Engine._ALPHA_MULTIPLY = 4;
  13816. Engine._ALPHA_MAXIMIZED = 5;
  13817. Engine._ALPHA_ONEONE = 6;
  13818. Engine._ALPHA_PREMULTIPLIED = 7;
  13819. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13820. Engine._ALPHA_INTERPOLATE = 9;
  13821. Engine._ALPHA_SCREENMODE = 10;
  13822. Engine._DELAYLOADSTATE_NONE = 0;
  13823. Engine._DELAYLOADSTATE_LOADED = 1;
  13824. Engine._DELAYLOADSTATE_LOADING = 2;
  13825. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13826. Engine._TEXTUREFORMAT_ALPHA = 0;
  13827. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13828. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13829. Engine._TEXTUREFORMAT_RGB = 4;
  13830. Engine._TEXTUREFORMAT_RGBA = 5;
  13831. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13832. Engine._TEXTURETYPE_FLOAT = 1;
  13833. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13834. // Depht or Stencil test Constants.
  13835. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13836. 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.
  13837. 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.
  13838. 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.
  13839. 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.
  13840. 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.
  13841. 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.
  13842. 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.
  13843. // Stencil Actions Constants.
  13844. Engine._KEEP = 0x1E00;
  13845. Engine._REPLACE = 0x1E01;
  13846. Engine._INCR = 0x1E02;
  13847. Engine._DECR = 0x1E03;
  13848. Engine._INVERT = 0x150A;
  13849. Engine._INCR_WRAP = 0x8507;
  13850. Engine._DECR_WRAP = 0x8508;
  13851. // Texture rescaling mode
  13852. Engine._SCALEMODE_FLOOR = 1;
  13853. Engine._SCALEMODE_NEAREST = 2;
  13854. Engine._SCALEMODE_CEILING = 3;
  13855. // Updatable statics so stick with vars here
  13856. Engine.CollisionsEpsilon = 0.001;
  13857. Engine.CodeRepository = "src/";
  13858. Engine.ShadersRepository = "src/Shaders/";
  13859. return Engine;
  13860. }());
  13861. BABYLON.Engine = Engine;
  13862. })(BABYLON || (BABYLON = {}));
  13863. //# sourceMappingURL=babylon.engine.js.map
  13864. var BABYLON;
  13865. (function (BABYLON) {
  13866. /**
  13867. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13868. */
  13869. var Node = /** @class */ (function () {
  13870. /**
  13871. * @constructor
  13872. * @param {string} name - the name and id to be given to this node
  13873. * @param {BABYLON.Scene} the scene this node will be added to
  13874. */
  13875. function Node(name, scene) {
  13876. if (scene === void 0) { scene = null; }
  13877. this.state = "";
  13878. this.metadata = null;
  13879. this.doNotSerialize = false;
  13880. this.animations = new Array();
  13881. this._ranges = {};
  13882. this._isEnabled = true;
  13883. this._isReady = true;
  13884. this._currentRenderId = -1;
  13885. this._parentRenderId = -1;
  13886. /**
  13887. * An event triggered when the mesh is disposed.
  13888. * @type {BABYLON.Observable}
  13889. */
  13890. this.onDisposeObservable = new BABYLON.Observable();
  13891. // Behaviors
  13892. this._behaviors = new Array();
  13893. this.name = name;
  13894. this.id = name;
  13895. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13896. this.uniqueId = this._scene.getUniqueId();
  13897. this._initCache();
  13898. }
  13899. Object.defineProperty(Node.prototype, "parent", {
  13900. get: function () {
  13901. return this._parentNode;
  13902. },
  13903. set: function (parent) {
  13904. if (this._parentNode === parent) {
  13905. return;
  13906. }
  13907. // Remove self from list of children of parent
  13908. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13909. var index = this._parentNode._children.indexOf(this);
  13910. if (index !== -1) {
  13911. this._parentNode._children.splice(index, 1);
  13912. }
  13913. }
  13914. // Store new parent
  13915. this._parentNode = parent;
  13916. // Add as child to new parent
  13917. if (this._parentNode) {
  13918. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13919. this._parentNode._children = new Array();
  13920. }
  13921. this._parentNode._children.push(this);
  13922. }
  13923. },
  13924. enumerable: true,
  13925. configurable: true
  13926. });
  13927. Node.prototype.getClassName = function () {
  13928. return "Node";
  13929. };
  13930. Object.defineProperty(Node.prototype, "onDispose", {
  13931. set: function (callback) {
  13932. if (this._onDisposeObserver) {
  13933. this.onDisposeObservable.remove(this._onDisposeObserver);
  13934. }
  13935. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13936. },
  13937. enumerable: true,
  13938. configurable: true
  13939. });
  13940. Node.prototype.getScene = function () {
  13941. return this._scene;
  13942. };
  13943. Node.prototype.getEngine = function () {
  13944. return this._scene.getEngine();
  13945. };
  13946. Node.prototype.addBehavior = function (behavior) {
  13947. var _this = this;
  13948. var index = this._behaviors.indexOf(behavior);
  13949. if (index !== -1) {
  13950. return this;
  13951. }
  13952. behavior.init();
  13953. if (this._scene.isLoading) {
  13954. // We defer the attach when the scene will be loaded
  13955. var observer = this._scene.onDataLoadedObservable.add(function () {
  13956. behavior.attach(_this);
  13957. setTimeout(function () {
  13958. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13959. _this._scene.onDataLoadedObservable.remove(observer);
  13960. }, 0);
  13961. });
  13962. }
  13963. else {
  13964. behavior.attach(this);
  13965. }
  13966. this._behaviors.push(behavior);
  13967. return this;
  13968. };
  13969. Node.prototype.removeBehavior = function (behavior) {
  13970. var index = this._behaviors.indexOf(behavior);
  13971. if (index === -1) {
  13972. return this;
  13973. }
  13974. this._behaviors[index].detach();
  13975. this._behaviors.splice(index, 1);
  13976. return this;
  13977. };
  13978. Object.defineProperty(Node.prototype, "behaviors", {
  13979. get: function () {
  13980. return this._behaviors;
  13981. },
  13982. enumerable: true,
  13983. configurable: true
  13984. });
  13985. Node.prototype.getBehaviorByName = function (name) {
  13986. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13987. var behavior = _a[_i];
  13988. if (behavior.name === name) {
  13989. return behavior;
  13990. }
  13991. }
  13992. return null;
  13993. };
  13994. // override it in derived class
  13995. Node.prototype.getWorldMatrix = function () {
  13996. return BABYLON.Matrix.Identity();
  13997. };
  13998. // override it in derived class if you add new variables to the cache
  13999. // and call the parent class method
  14000. Node.prototype._initCache = function () {
  14001. this._cache = {};
  14002. this._cache.parent = undefined;
  14003. };
  14004. Node.prototype.updateCache = function (force) {
  14005. if (!force && this.isSynchronized())
  14006. return;
  14007. this._cache.parent = this.parent;
  14008. this._updateCache();
  14009. };
  14010. // override it in derived class if you add new variables to the cache
  14011. // and call the parent class method if !ignoreParentClass
  14012. Node.prototype._updateCache = function (ignoreParentClass) {
  14013. };
  14014. // override it in derived class if you add new variables to the cache
  14015. Node.prototype._isSynchronized = function () {
  14016. return true;
  14017. };
  14018. Node.prototype._markSyncedWithParent = function () {
  14019. if (this.parent) {
  14020. this._parentRenderId = this.parent._currentRenderId;
  14021. }
  14022. };
  14023. Node.prototype.isSynchronizedWithParent = function () {
  14024. if (!this.parent) {
  14025. return true;
  14026. }
  14027. if (this._parentRenderId !== this.parent._currentRenderId) {
  14028. return false;
  14029. }
  14030. return this.parent.isSynchronized();
  14031. };
  14032. Node.prototype.isSynchronized = function (updateCache) {
  14033. var check = this.hasNewParent();
  14034. check = check || !this.isSynchronizedWithParent();
  14035. check = check || !this._isSynchronized();
  14036. if (updateCache)
  14037. this.updateCache(true);
  14038. return !check;
  14039. };
  14040. Node.prototype.hasNewParent = function (update) {
  14041. if (this._cache.parent === this.parent)
  14042. return false;
  14043. if (update)
  14044. this._cache.parent = this.parent;
  14045. return true;
  14046. };
  14047. /**
  14048. * Is this node ready to be used/rendered
  14049. * @return {boolean} is it ready
  14050. */
  14051. Node.prototype.isReady = function () {
  14052. return this._isReady;
  14053. };
  14054. /**
  14055. * Is this node enabled.
  14056. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  14057. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  14058. * @return {boolean} whether this node (and its parent) is enabled.
  14059. * @see setEnabled
  14060. */
  14061. Node.prototype.isEnabled = function (checkAncestors) {
  14062. if (checkAncestors === void 0) { checkAncestors = true; }
  14063. if (checkAncestors === false) {
  14064. return this._isEnabled;
  14065. }
  14066. if (this._isEnabled === false) {
  14067. return false;
  14068. }
  14069. if (this.parent !== undefined && this.parent !== null) {
  14070. return this.parent.isEnabled(checkAncestors);
  14071. }
  14072. return true;
  14073. };
  14074. /**
  14075. * Set the enabled state of this node.
  14076. * @param {boolean} value - the new enabled state
  14077. * @see isEnabled
  14078. */
  14079. Node.prototype.setEnabled = function (value) {
  14080. this._isEnabled = value;
  14081. };
  14082. /**
  14083. * Is this node a descendant of the given node.
  14084. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14085. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14086. * @see parent
  14087. */
  14088. Node.prototype.isDescendantOf = function (ancestor) {
  14089. if (this.parent) {
  14090. if (this.parent === ancestor) {
  14091. return true;
  14092. }
  14093. return this.parent.isDescendantOf(ancestor);
  14094. }
  14095. return false;
  14096. };
  14097. /**
  14098. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14099. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14100. * @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.
  14101. * @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.
  14102. */
  14103. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14104. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14105. if (!this._children) {
  14106. return;
  14107. }
  14108. for (var index = 0; index < this._children.length; index++) {
  14109. var item = this._children[index];
  14110. if (!predicate || predicate(item)) {
  14111. results.push(item);
  14112. }
  14113. if (!directDescendantsOnly) {
  14114. item._getDescendants(results, false, predicate);
  14115. }
  14116. }
  14117. };
  14118. /**
  14119. * Will return all nodes that have this node as ascendant.
  14120. * @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.
  14121. * @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.
  14122. * @return {BABYLON.Node[]} all children nodes of all types.
  14123. */
  14124. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14125. var results = new Array();
  14126. this._getDescendants(results, directDescendantsOnly, predicate);
  14127. return results;
  14128. };
  14129. /**
  14130. * Get all child-meshes of this node.
  14131. */
  14132. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14133. var results = [];
  14134. this._getDescendants(results, directDescendantsOnly, function (node) {
  14135. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14136. });
  14137. return results;
  14138. };
  14139. /**
  14140. * Get all child-transformNodes of this node.
  14141. */
  14142. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14143. var results = [];
  14144. this._getDescendants(results, directDescendantsOnly, function (node) {
  14145. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14146. });
  14147. return results;
  14148. };
  14149. /**
  14150. * Get all direct children of this node.
  14151. */
  14152. Node.prototype.getChildren = function (predicate) {
  14153. return this.getDescendants(true, predicate);
  14154. };
  14155. Node.prototype._setReady = function (state) {
  14156. if (state === this._isReady) {
  14157. return;
  14158. }
  14159. if (!state) {
  14160. this._isReady = false;
  14161. return;
  14162. }
  14163. this._isReady = true;
  14164. if (this.onReady) {
  14165. this.onReady(this);
  14166. }
  14167. };
  14168. Node.prototype.getAnimationByName = function (name) {
  14169. for (var i = 0; i < this.animations.length; i++) {
  14170. var animation = this.animations[i];
  14171. if (animation.name === name) {
  14172. return animation;
  14173. }
  14174. }
  14175. return null;
  14176. };
  14177. Node.prototype.createAnimationRange = function (name, from, to) {
  14178. // check name not already in use
  14179. if (!this._ranges[name]) {
  14180. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14181. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14182. if (this.animations[i]) {
  14183. this.animations[i].createRange(name, from, to);
  14184. }
  14185. }
  14186. }
  14187. };
  14188. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14189. if (deleteFrames === void 0) { deleteFrames = true; }
  14190. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14191. if (this.animations[i]) {
  14192. this.animations[i].deleteRange(name, deleteFrames);
  14193. }
  14194. }
  14195. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14196. };
  14197. Node.prototype.getAnimationRange = function (name) {
  14198. return this._ranges[name];
  14199. };
  14200. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14201. var range = this.getAnimationRange(name);
  14202. if (!range) {
  14203. return;
  14204. }
  14205. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14206. };
  14207. Node.prototype.serializeAnimationRanges = function () {
  14208. var serializationRanges = [];
  14209. for (var name in this._ranges) {
  14210. var localRange = this._ranges[name];
  14211. if (!localRange) {
  14212. continue;
  14213. }
  14214. var range = {};
  14215. range.name = name;
  14216. range.from = localRange.from;
  14217. range.to = localRange.to;
  14218. serializationRanges.push(range);
  14219. }
  14220. return serializationRanges;
  14221. };
  14222. // override it in derived class
  14223. Node.prototype.computeWorldMatrix = function (force) {
  14224. return BABYLON.Matrix.Identity();
  14225. };
  14226. Node.prototype.dispose = function () {
  14227. this.parent = null;
  14228. // Callback
  14229. this.onDisposeObservable.notifyObservers(this);
  14230. this.onDisposeObservable.clear();
  14231. // Behaviors
  14232. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14233. var behavior = _a[_i];
  14234. behavior.detach();
  14235. }
  14236. this._behaviors = [];
  14237. };
  14238. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14239. if (parsedNode.ranges) {
  14240. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14241. var data = parsedNode.ranges[index];
  14242. node.createAnimationRange(data.name, data.from, data.to);
  14243. }
  14244. }
  14245. };
  14246. __decorate([
  14247. BABYLON.serialize()
  14248. ], Node.prototype, "name", void 0);
  14249. __decorate([
  14250. BABYLON.serialize()
  14251. ], Node.prototype, "id", void 0);
  14252. __decorate([
  14253. BABYLON.serialize()
  14254. ], Node.prototype, "uniqueId", void 0);
  14255. __decorate([
  14256. BABYLON.serialize()
  14257. ], Node.prototype, "state", void 0);
  14258. __decorate([
  14259. BABYLON.serialize()
  14260. ], Node.prototype, "metadata", void 0);
  14261. return Node;
  14262. }());
  14263. BABYLON.Node = Node;
  14264. })(BABYLON || (BABYLON = {}));
  14265. //# sourceMappingURL=babylon.node.js.map
  14266. var BABYLON;
  14267. (function (BABYLON) {
  14268. var BoundingSphere = /** @class */ (function () {
  14269. function BoundingSphere(minimum, maximum) {
  14270. this.minimum = minimum;
  14271. this.maximum = maximum;
  14272. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14273. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14274. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14275. this.radius = distance * 0.5;
  14276. this.centerWorld = BABYLON.Vector3.Zero();
  14277. this._update(BABYLON.Matrix.Identity());
  14278. }
  14279. // Methods
  14280. BoundingSphere.prototype._update = function (world) {
  14281. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14282. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14283. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14284. };
  14285. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14286. for (var i = 0; i < 6; i++) {
  14287. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14288. return false;
  14289. }
  14290. return true;
  14291. };
  14292. BoundingSphere.prototype.intersectsPoint = function (point) {
  14293. var x = this.centerWorld.x - point.x;
  14294. var y = this.centerWorld.y - point.y;
  14295. var z = this.centerWorld.z - point.z;
  14296. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14297. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14298. return false;
  14299. return true;
  14300. };
  14301. // Statics
  14302. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14303. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14304. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14305. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14306. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14307. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14308. return false;
  14309. return true;
  14310. };
  14311. return BoundingSphere;
  14312. }());
  14313. BABYLON.BoundingSphere = BoundingSphere;
  14314. })(BABYLON || (BABYLON = {}));
  14315. //# sourceMappingURL=babylon.boundingSphere.js.map
  14316. var BABYLON;
  14317. (function (BABYLON) {
  14318. var BoundingBox = /** @class */ (function () {
  14319. function BoundingBox(minimum, maximum) {
  14320. this.minimum = minimum;
  14321. this.maximum = maximum;
  14322. this.vectors = new Array();
  14323. this.vectorsWorld = new Array();
  14324. // Bounding vectors
  14325. this.vectors.push(this.minimum.clone());
  14326. this.vectors.push(this.maximum.clone());
  14327. this.vectors.push(this.minimum.clone());
  14328. this.vectors[2].x = this.maximum.x;
  14329. this.vectors.push(this.minimum.clone());
  14330. this.vectors[3].y = this.maximum.y;
  14331. this.vectors.push(this.minimum.clone());
  14332. this.vectors[4].z = this.maximum.z;
  14333. this.vectors.push(this.maximum.clone());
  14334. this.vectors[5].z = this.minimum.z;
  14335. this.vectors.push(this.maximum.clone());
  14336. this.vectors[6].x = this.minimum.x;
  14337. this.vectors.push(this.maximum.clone());
  14338. this.vectors[7].y = this.minimum.y;
  14339. // OBB
  14340. this.center = this.maximum.add(this.minimum).scale(0.5);
  14341. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14342. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14343. // World
  14344. for (var index = 0; index < this.vectors.length; index++) {
  14345. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14346. }
  14347. this.minimumWorld = BABYLON.Vector3.Zero();
  14348. this.maximumWorld = BABYLON.Vector3.Zero();
  14349. this.centerWorld = BABYLON.Vector3.Zero();
  14350. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14351. this._update(BABYLON.Matrix.Identity());
  14352. }
  14353. // Methods
  14354. BoundingBox.prototype.getWorldMatrix = function () {
  14355. return this._worldMatrix;
  14356. };
  14357. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14358. this._worldMatrix.copyFrom(matrix);
  14359. return this;
  14360. };
  14361. BoundingBox.prototype._update = function (world) {
  14362. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14363. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14364. for (var index = 0; index < this.vectors.length; index++) {
  14365. var v = this.vectorsWorld[index];
  14366. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14367. if (v.x < this.minimumWorld.x)
  14368. this.minimumWorld.x = v.x;
  14369. if (v.y < this.minimumWorld.y)
  14370. this.minimumWorld.y = v.y;
  14371. if (v.z < this.minimumWorld.z)
  14372. this.minimumWorld.z = v.z;
  14373. if (v.x > this.maximumWorld.x)
  14374. this.maximumWorld.x = v.x;
  14375. if (v.y > this.maximumWorld.y)
  14376. this.maximumWorld.y = v.y;
  14377. if (v.z > this.maximumWorld.z)
  14378. this.maximumWorld.z = v.z;
  14379. }
  14380. // Extend
  14381. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14382. this.extendSizeWorld.scaleInPlace(0.5);
  14383. // OBB
  14384. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14385. this.centerWorld.scaleInPlace(0.5);
  14386. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14387. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14388. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14389. this._worldMatrix = world;
  14390. };
  14391. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14392. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14393. };
  14394. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14395. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14396. };
  14397. BoundingBox.prototype.intersectsPoint = function (point) {
  14398. var delta = -BABYLON.Epsilon;
  14399. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14400. return false;
  14401. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14402. return false;
  14403. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14404. return false;
  14405. return true;
  14406. };
  14407. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14408. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14409. };
  14410. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14411. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14412. return false;
  14413. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14414. return false;
  14415. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14416. return false;
  14417. return true;
  14418. };
  14419. // Statics
  14420. BoundingBox.Intersects = function (box0, box1) {
  14421. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14422. return false;
  14423. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14424. return false;
  14425. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14426. return false;
  14427. return true;
  14428. };
  14429. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14430. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14431. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14432. return (num <= (sphereRadius * sphereRadius));
  14433. };
  14434. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14435. for (var p = 0; p < 6; p++) {
  14436. for (var i = 0; i < 8; i++) {
  14437. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14438. return false;
  14439. }
  14440. }
  14441. }
  14442. return true;
  14443. };
  14444. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14445. for (var p = 0; p < 6; p++) {
  14446. var inCount = 8;
  14447. for (var i = 0; i < 8; i++) {
  14448. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14449. --inCount;
  14450. }
  14451. else {
  14452. break;
  14453. }
  14454. }
  14455. if (inCount === 0)
  14456. return false;
  14457. }
  14458. return true;
  14459. };
  14460. return BoundingBox;
  14461. }());
  14462. BABYLON.BoundingBox = BoundingBox;
  14463. })(BABYLON || (BABYLON = {}));
  14464. //# sourceMappingURL=babylon.boundingBox.js.map
  14465. var BABYLON;
  14466. (function (BABYLON) {
  14467. var computeBoxExtents = function (axis, box) {
  14468. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14469. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14470. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14471. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14472. var r = r0 + r1 + r2;
  14473. return {
  14474. min: p - r,
  14475. max: p + r
  14476. };
  14477. };
  14478. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14479. var axisOverlap = function (axis, box0, box1) {
  14480. var result0 = computeBoxExtents(axis, box0);
  14481. var result1 = computeBoxExtents(axis, box1);
  14482. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14483. };
  14484. var BoundingInfo = /** @class */ (function () {
  14485. function BoundingInfo(minimum, maximum) {
  14486. this.minimum = minimum;
  14487. this.maximum = maximum;
  14488. this._isLocked = false;
  14489. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14490. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14491. }
  14492. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14493. get: function () {
  14494. return this._isLocked;
  14495. },
  14496. set: function (value) {
  14497. this._isLocked = value;
  14498. },
  14499. enumerable: true,
  14500. configurable: true
  14501. });
  14502. // Methods
  14503. BoundingInfo.prototype.update = function (world) {
  14504. if (this._isLocked) {
  14505. return;
  14506. }
  14507. this.boundingBox._update(world);
  14508. this.boundingSphere._update(world);
  14509. };
  14510. /**
  14511. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14512. * @param center New center of the bounding info
  14513. * @param extend New extend of the bounding info
  14514. */
  14515. BoundingInfo.prototype.centerOn = function (center, extend) {
  14516. this.minimum = center.subtract(extend);
  14517. this.maximum = center.add(extend);
  14518. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14519. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14520. return this;
  14521. };
  14522. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14523. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14524. return false;
  14525. return this.boundingBox.isInFrustum(frustumPlanes);
  14526. };
  14527. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14528. /**
  14529. * Gets the world distance between the min and max points of the bounding box
  14530. */
  14531. get: function () {
  14532. var boundingBox = this.boundingBox;
  14533. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14534. return size.length();
  14535. },
  14536. enumerable: true,
  14537. configurable: true
  14538. });
  14539. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14540. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14541. };
  14542. BoundingInfo.prototype._checkCollision = function (collider) {
  14543. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14544. };
  14545. BoundingInfo.prototype.intersectsPoint = function (point) {
  14546. if (!this.boundingSphere.centerWorld) {
  14547. return false;
  14548. }
  14549. if (!this.boundingSphere.intersectsPoint(point)) {
  14550. return false;
  14551. }
  14552. if (!this.boundingBox.intersectsPoint(point)) {
  14553. return false;
  14554. }
  14555. return true;
  14556. };
  14557. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14558. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14559. return false;
  14560. }
  14561. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14562. return false;
  14563. }
  14564. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14565. return false;
  14566. }
  14567. if (!precise) {
  14568. return true;
  14569. }
  14570. var box0 = this.boundingBox;
  14571. var box1 = boundingInfo.boundingBox;
  14572. if (!axisOverlap(box0.directions[0], box0, box1))
  14573. return false;
  14574. if (!axisOverlap(box0.directions[1], box0, box1))
  14575. return false;
  14576. if (!axisOverlap(box0.directions[2], box0, box1))
  14577. return false;
  14578. if (!axisOverlap(box1.directions[0], box0, box1))
  14579. return false;
  14580. if (!axisOverlap(box1.directions[1], box0, box1))
  14581. return false;
  14582. if (!axisOverlap(box1.directions[2], box0, box1))
  14583. return false;
  14584. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14585. return false;
  14586. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14587. return false;
  14588. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14589. return false;
  14590. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14591. return false;
  14592. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14593. return false;
  14594. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14595. return false;
  14596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14597. return false;
  14598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14599. return false;
  14600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14601. return false;
  14602. return true;
  14603. };
  14604. return BoundingInfo;
  14605. }());
  14606. BABYLON.BoundingInfo = BoundingInfo;
  14607. })(BABYLON || (BABYLON = {}));
  14608. //# sourceMappingURL=babylon.boundingInfo.js.map
  14609. var BABYLON;
  14610. (function (BABYLON) {
  14611. var TransformNode = /** @class */ (function (_super) {
  14612. __extends(TransformNode, _super);
  14613. function TransformNode(name, scene, isPure) {
  14614. if (scene === void 0) { scene = null; }
  14615. if (isPure === void 0) { isPure = true; }
  14616. var _this = _super.call(this, name, scene) || this;
  14617. // Properties
  14618. _this._rotation = BABYLON.Vector3.Zero();
  14619. _this._scaling = BABYLON.Vector3.One();
  14620. _this._isDirty = false;
  14621. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14622. _this.scalingDeterminant = 1;
  14623. _this.infiniteDistance = false;
  14624. _this.position = BABYLON.Vector3.Zero();
  14625. _this._localWorld = BABYLON.Matrix.Zero();
  14626. _this._worldMatrix = BABYLON.Matrix.Zero();
  14627. _this._worldMatrixDeterminant = 0;
  14628. _this._absolutePosition = BABYLON.Vector3.Zero();
  14629. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14630. _this._postMultiplyPivotMatrix = false;
  14631. _this._isWorldMatrixFrozen = false;
  14632. /**
  14633. * An event triggered after the world matrix is updated
  14634. * @type {BABYLON.Observable}
  14635. */
  14636. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14637. _this._nonUniformScaling = false;
  14638. if (isPure) {
  14639. _this.getScene().addTransformNode(_this);
  14640. }
  14641. return _this;
  14642. }
  14643. Object.defineProperty(TransformNode.prototype, "rotation", {
  14644. /**
  14645. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14646. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14647. * Default : (0.0, 0.0, 0.0)
  14648. */
  14649. get: function () {
  14650. return this._rotation;
  14651. },
  14652. set: function (newRotation) {
  14653. this._rotation = newRotation;
  14654. },
  14655. enumerable: true,
  14656. configurable: true
  14657. });
  14658. Object.defineProperty(TransformNode.prototype, "scaling", {
  14659. /**
  14660. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14661. * Default : (1.0, 1.0, 1.0)
  14662. */
  14663. get: function () {
  14664. return this._scaling;
  14665. },
  14666. /**
  14667. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14668. * Default : (1.0, 1.0, 1.0)
  14669. */
  14670. set: function (newScaling) {
  14671. this._scaling = newScaling;
  14672. },
  14673. enumerable: true,
  14674. configurable: true
  14675. });
  14676. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14677. /**
  14678. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14679. * It's null by default.
  14680. * 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)
  14681. */
  14682. get: function () {
  14683. return this._rotationQuaternion;
  14684. },
  14685. set: function (quaternion) {
  14686. this._rotationQuaternion = quaternion;
  14687. //reset the rotation vector.
  14688. if (quaternion && this.rotation.length()) {
  14689. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14690. }
  14691. },
  14692. enumerable: true,
  14693. configurable: true
  14694. });
  14695. /**
  14696. * Returns the latest update of the World matrix
  14697. * Returns a Matrix.
  14698. */
  14699. TransformNode.prototype.getWorldMatrix = function () {
  14700. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14701. this.computeWorldMatrix();
  14702. }
  14703. return this._worldMatrix;
  14704. };
  14705. /**
  14706. * Returns the latest update of the World matrix determinant.
  14707. */
  14708. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14709. return this._worldMatrixDeterminant;
  14710. };
  14711. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14712. /**
  14713. * Returns directly the latest state of the mesh World matrix.
  14714. * A Matrix is returned.
  14715. */
  14716. get: function () {
  14717. return this._worldMatrix;
  14718. },
  14719. enumerable: true,
  14720. configurable: true
  14721. });
  14722. /**
  14723. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14724. * Returns the AbstractMesh.
  14725. */
  14726. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14727. this._poseMatrix.copyFrom(matrix);
  14728. return this;
  14729. };
  14730. /**
  14731. * Returns the mesh Pose matrix.
  14732. * Returned object : Matrix
  14733. */
  14734. TransformNode.prototype.getPoseMatrix = function () {
  14735. return this._poseMatrix;
  14736. };
  14737. TransformNode.prototype._isSynchronized = function () {
  14738. if (this._isDirty) {
  14739. return false;
  14740. }
  14741. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14742. return false;
  14743. if (this._cache.pivotMatrixUpdated) {
  14744. return false;
  14745. }
  14746. if (this.infiniteDistance) {
  14747. return false;
  14748. }
  14749. if (!this._cache.position.equals(this.position))
  14750. return false;
  14751. if (this.rotationQuaternion) {
  14752. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14753. return false;
  14754. }
  14755. if (!this._cache.rotation.equals(this.rotation))
  14756. return false;
  14757. if (!this._cache.scaling.equals(this.scaling))
  14758. return false;
  14759. return true;
  14760. };
  14761. TransformNode.prototype._initCache = function () {
  14762. _super.prototype._initCache.call(this);
  14763. this._cache.localMatrixUpdated = false;
  14764. this._cache.position = BABYLON.Vector3.Zero();
  14765. this._cache.scaling = BABYLON.Vector3.Zero();
  14766. this._cache.rotation = BABYLON.Vector3.Zero();
  14767. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14768. this._cache.billboardMode = -1;
  14769. };
  14770. TransformNode.prototype.markAsDirty = function (property) {
  14771. if (property === "rotation") {
  14772. this.rotationQuaternion = null;
  14773. }
  14774. this._currentRenderId = Number.MAX_VALUE;
  14775. this._isDirty = true;
  14776. return this;
  14777. };
  14778. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14779. /**
  14780. * Returns the current mesh absolute position.
  14781. * Retuns a Vector3.
  14782. */
  14783. get: function () {
  14784. return this._absolutePosition;
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. /**
  14790. * Sets a new pivot matrix to the mesh.
  14791. * Returns the AbstractMesh.
  14792. */
  14793. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14794. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14795. this._pivotMatrix = matrix.clone();
  14796. this._cache.pivotMatrixUpdated = true;
  14797. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14798. if (this._postMultiplyPivotMatrix) {
  14799. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14800. }
  14801. return this;
  14802. };
  14803. /**
  14804. * Returns the mesh pivot matrix.
  14805. * Default : Identity.
  14806. * A Matrix is returned.
  14807. */
  14808. TransformNode.prototype.getPivotMatrix = function () {
  14809. return this._pivotMatrix;
  14810. };
  14811. /**
  14812. * Prevents the World matrix to be computed any longer.
  14813. * Returns the AbstractMesh.
  14814. */
  14815. TransformNode.prototype.freezeWorldMatrix = function () {
  14816. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14817. this.computeWorldMatrix(true);
  14818. this._isWorldMatrixFrozen = true;
  14819. return this;
  14820. };
  14821. /**
  14822. * Allows back the World matrix computation.
  14823. * Returns the AbstractMesh.
  14824. */
  14825. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14826. this._isWorldMatrixFrozen = false;
  14827. this.computeWorldMatrix(true);
  14828. return this;
  14829. };
  14830. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14831. /**
  14832. * True if the World matrix has been frozen.
  14833. * Returns a boolean.
  14834. */
  14835. get: function () {
  14836. return this._isWorldMatrixFrozen;
  14837. },
  14838. enumerable: true,
  14839. configurable: true
  14840. });
  14841. /**
  14842. * Retuns the mesh absolute position in the World.
  14843. * Returns a Vector3.
  14844. */
  14845. TransformNode.prototype.getAbsolutePosition = function () {
  14846. this.computeWorldMatrix();
  14847. return this._absolutePosition;
  14848. };
  14849. /**
  14850. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14851. * Returns the AbstractMesh.
  14852. */
  14853. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14854. if (!absolutePosition) {
  14855. return this;
  14856. }
  14857. var absolutePositionX;
  14858. var absolutePositionY;
  14859. var absolutePositionZ;
  14860. if (absolutePosition.x === undefined) {
  14861. if (arguments.length < 3) {
  14862. return this;
  14863. }
  14864. absolutePositionX = arguments[0];
  14865. absolutePositionY = arguments[1];
  14866. absolutePositionZ = arguments[2];
  14867. }
  14868. else {
  14869. absolutePositionX = absolutePosition.x;
  14870. absolutePositionY = absolutePosition.y;
  14871. absolutePositionZ = absolutePosition.z;
  14872. }
  14873. if (this.parent) {
  14874. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14875. invertParentWorldMatrix.invert();
  14876. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14877. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14878. }
  14879. else {
  14880. this.position.x = absolutePositionX;
  14881. this.position.y = absolutePositionY;
  14882. this.position.z = absolutePositionZ;
  14883. }
  14884. return this;
  14885. };
  14886. /**
  14887. * Sets the mesh position in its local space.
  14888. * Returns the AbstractMesh.
  14889. */
  14890. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14891. this.computeWorldMatrix();
  14892. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14893. return this;
  14894. };
  14895. /**
  14896. * Returns the mesh position in the local space from the current World matrix values.
  14897. * Returns a new Vector3.
  14898. */
  14899. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14900. this.computeWorldMatrix();
  14901. var invLocalWorldMatrix = this._localWorld.clone();
  14902. invLocalWorldMatrix.invert();
  14903. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14904. };
  14905. /**
  14906. * Translates the mesh along the passed Vector3 in its local space.
  14907. * Returns the AbstractMesh.
  14908. */
  14909. TransformNode.prototype.locallyTranslate = function (vector3) {
  14910. this.computeWorldMatrix(true);
  14911. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14912. return this;
  14913. };
  14914. /**
  14915. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14916. * @param targetPoint the position (must be in same space as current mesh) to look at
  14917. * @param yawCor optional yaw (y-axis) correction in radians
  14918. * @param pitchCor optional pitch (x-axis) correction in radians
  14919. * @param rollCor optional roll (z-axis) correction in radians
  14920. * @param space the choosen space of the target
  14921. * @returns the TransformNode.
  14922. */
  14923. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14924. if (yawCor === void 0) { yawCor = 0; }
  14925. if (pitchCor === void 0) { pitchCor = 0; }
  14926. if (rollCor === void 0) { rollCor = 0; }
  14927. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14928. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14929. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14930. targetPoint.subtractToRef(pos, dv);
  14931. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14932. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14933. var pitch = Math.atan2(dv.y, len);
  14934. if (this.rotationQuaternion) {
  14935. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14936. }
  14937. else {
  14938. this.rotation.x = pitch + pitchCor;
  14939. this.rotation.y = yaw + yawCor;
  14940. this.rotation.z = rollCor;
  14941. }
  14942. return this;
  14943. };
  14944. /**
  14945. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14946. * This Vector3 is expressed in the World space.
  14947. */
  14948. TransformNode.prototype.getDirection = function (localAxis) {
  14949. var result = BABYLON.Vector3.Zero();
  14950. this.getDirectionToRef(localAxis, result);
  14951. return result;
  14952. };
  14953. /**
  14954. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14955. * localAxis is expressed in the mesh local space.
  14956. * result is computed in the Wordl space from the mesh World matrix.
  14957. * Returns the AbstractMesh.
  14958. */
  14959. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14960. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14961. return this;
  14962. };
  14963. TransformNode.prototype.setPivotPoint = function (point, space) {
  14964. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14965. if (this.getScene().getRenderId() == 0) {
  14966. this.computeWorldMatrix(true);
  14967. }
  14968. var wm = this.getWorldMatrix();
  14969. if (space == BABYLON.Space.WORLD) {
  14970. var tmat = BABYLON.Tmp.Matrix[0];
  14971. wm.invertToRef(tmat);
  14972. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14973. }
  14974. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14975. this._pivotMatrix.m[12] = -point.x;
  14976. this._pivotMatrix.m[13] = -point.y;
  14977. this._pivotMatrix.m[14] = -point.z;
  14978. this._cache.pivotMatrixUpdated = true;
  14979. return this;
  14980. };
  14981. /**
  14982. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14983. */
  14984. TransformNode.prototype.getPivotPoint = function () {
  14985. var point = BABYLON.Vector3.Zero();
  14986. this.getPivotPointToRef(point);
  14987. return point;
  14988. };
  14989. /**
  14990. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14991. * Returns the AbstractMesh.
  14992. */
  14993. TransformNode.prototype.getPivotPointToRef = function (result) {
  14994. result.x = -this._pivotMatrix.m[12];
  14995. result.y = -this._pivotMatrix.m[13];
  14996. result.z = -this._pivotMatrix.m[14];
  14997. return this;
  14998. };
  14999. /**
  15000. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15001. */
  15002. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15003. var point = BABYLON.Vector3.Zero();
  15004. this.getAbsolutePivotPointToRef(point);
  15005. return point;
  15006. };
  15007. /**
  15008. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15009. * Returns the AbstractMesh.
  15010. */
  15011. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15012. result.x = this._pivotMatrix.m[12];
  15013. result.y = this._pivotMatrix.m[13];
  15014. result.z = this._pivotMatrix.m[14];
  15015. this.getPivotPointToRef(result);
  15016. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15017. return this;
  15018. };
  15019. /**
  15020. * Defines the passed node as the parent of the current node.
  15021. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15022. * Returns the TransformNode.
  15023. */
  15024. TransformNode.prototype.setParent = function (node) {
  15025. if (node === null) {
  15026. var rotation = BABYLON.Tmp.Quaternion[0];
  15027. var position = BABYLON.Tmp.Vector3[0];
  15028. var scale = BABYLON.Tmp.Vector3[1];
  15029. if (this.parent && this.parent.computeWorldMatrix) {
  15030. this.parent.computeWorldMatrix(true);
  15031. }
  15032. this.computeWorldMatrix(true);
  15033. this.getWorldMatrix().decompose(scale, rotation, position);
  15034. if (this.rotationQuaternion) {
  15035. this.rotationQuaternion.copyFrom(rotation);
  15036. }
  15037. else {
  15038. rotation.toEulerAnglesToRef(this.rotation);
  15039. }
  15040. this.scaling.x = scale.x;
  15041. this.scaling.y = scale.y;
  15042. this.scaling.z = scale.z;
  15043. this.position.x = position.x;
  15044. this.position.y = position.y;
  15045. this.position.z = position.z;
  15046. }
  15047. else {
  15048. var rotation = BABYLON.Tmp.Quaternion[0];
  15049. var position = BABYLON.Tmp.Vector3[0];
  15050. var scale = BABYLON.Tmp.Vector3[1];
  15051. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15052. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15053. this.computeWorldMatrix(true);
  15054. node.computeWorldMatrix(true);
  15055. node.getWorldMatrix().invertToRef(invParentMatrix);
  15056. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15057. diffMatrix.decompose(scale, rotation, position);
  15058. if (this.rotationQuaternion) {
  15059. this.rotationQuaternion.copyFrom(rotation);
  15060. }
  15061. else {
  15062. rotation.toEulerAnglesToRef(this.rotation);
  15063. }
  15064. this.position.x = position.x;
  15065. this.position.y = position.y;
  15066. this.position.z = position.z;
  15067. this.scaling.x = scale.x;
  15068. this.scaling.y = scale.y;
  15069. this.scaling.z = scale.z;
  15070. }
  15071. this.parent = node;
  15072. return this;
  15073. };
  15074. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15075. get: function () {
  15076. return this._nonUniformScaling;
  15077. },
  15078. enumerable: true,
  15079. configurable: true
  15080. });
  15081. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15082. if (this._nonUniformScaling === value) {
  15083. return false;
  15084. }
  15085. this._nonUniformScaling = true;
  15086. return true;
  15087. };
  15088. /**
  15089. * Attach the current TransformNode to another TransformNode associated with a bone
  15090. * @param bone Bone affecting the TransformNode
  15091. * @param affectedTransformNode TransformNode associated with the bone
  15092. */
  15093. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15094. this._transformToBoneReferal = affectedTransformNode;
  15095. this.parent = bone;
  15096. if (bone.getWorldMatrix().determinant() < 0) {
  15097. this.scalingDeterminant *= -1;
  15098. }
  15099. return this;
  15100. };
  15101. TransformNode.prototype.detachFromBone = function () {
  15102. if (!this.parent) {
  15103. return this;
  15104. }
  15105. if (this.parent.getWorldMatrix().determinant() < 0) {
  15106. this.scalingDeterminant *= -1;
  15107. }
  15108. this._transformToBoneReferal = null;
  15109. this.parent = null;
  15110. return this;
  15111. };
  15112. /**
  15113. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15114. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15115. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15116. * The passed axis is also normalized.
  15117. * Returns the AbstractMesh.
  15118. */
  15119. TransformNode.prototype.rotate = function (axis, amount, space) {
  15120. axis.normalize();
  15121. if (!this.rotationQuaternion) {
  15122. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15123. this.rotation = BABYLON.Vector3.Zero();
  15124. }
  15125. var rotationQuaternion;
  15126. if (!space || space === BABYLON.Space.LOCAL) {
  15127. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15128. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15129. }
  15130. else {
  15131. if (this.parent) {
  15132. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15133. invertParentWorldMatrix.invert();
  15134. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15135. }
  15136. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15137. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15138. }
  15139. return this;
  15140. };
  15141. /**
  15142. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15143. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15144. * The passed axis is also normalized.
  15145. * Returns the AbstractMesh.
  15146. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15147. */
  15148. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15149. axis.normalize();
  15150. if (!this.rotationQuaternion) {
  15151. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15152. this.rotation.copyFromFloats(0, 0, 0);
  15153. }
  15154. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15155. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15156. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15157. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15158. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15159. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15160. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15161. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15162. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15163. return this;
  15164. };
  15165. /**
  15166. * Translates the mesh along the axis vector for the passed distance in the given space.
  15167. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15168. * Returns the AbstractMesh.
  15169. */
  15170. TransformNode.prototype.translate = function (axis, distance, space) {
  15171. var displacementVector = axis.scale(distance);
  15172. if (!space || space === BABYLON.Space.LOCAL) {
  15173. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15174. this.setPositionWithLocalVector(tempV3);
  15175. }
  15176. else {
  15177. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15178. }
  15179. return this;
  15180. };
  15181. /**
  15182. * Adds a rotation step to the mesh current rotation.
  15183. * x, y, z are Euler angles expressed in radians.
  15184. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15185. * This means this rotation is made in the mesh local space only.
  15186. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15187. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15188. * ```javascript
  15189. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15190. * ```
  15191. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15192. * 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.
  15193. * Returns the AbstractMesh.
  15194. */
  15195. TransformNode.prototype.addRotation = function (x, y, z) {
  15196. var rotationQuaternion;
  15197. if (this.rotationQuaternion) {
  15198. rotationQuaternion = this.rotationQuaternion;
  15199. }
  15200. else {
  15201. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15202. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15203. }
  15204. var accumulation = BABYLON.Tmp.Quaternion[0];
  15205. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15206. rotationQuaternion.multiplyInPlace(accumulation);
  15207. if (!this.rotationQuaternion) {
  15208. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15209. }
  15210. return this;
  15211. };
  15212. /**
  15213. * Computes the mesh World matrix and returns it.
  15214. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15215. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15216. * If the parameter `force`is set to `true`, the actual computation is done.
  15217. * Returns the mesh World Matrix.
  15218. */
  15219. TransformNode.prototype.computeWorldMatrix = function (force) {
  15220. if (this._isWorldMatrixFrozen) {
  15221. return this._worldMatrix;
  15222. }
  15223. if (!force && this.isSynchronized(true)) {
  15224. return this._worldMatrix;
  15225. }
  15226. this._cache.position.copyFrom(this.position);
  15227. this._cache.scaling.copyFrom(this.scaling);
  15228. this._cache.pivotMatrixUpdated = false;
  15229. this._cache.billboardMode = this.billboardMode;
  15230. this._currentRenderId = this.getScene().getRenderId();
  15231. this._isDirty = false;
  15232. // Scaling
  15233. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15234. // Rotation
  15235. //rotate, if quaternion is set and rotation was used
  15236. if (this.rotationQuaternion) {
  15237. var len = this.rotation.length();
  15238. if (len) {
  15239. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15240. this.rotation.copyFromFloats(0, 0, 0);
  15241. }
  15242. }
  15243. if (this.rotationQuaternion) {
  15244. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15245. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15246. }
  15247. else {
  15248. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15249. this._cache.rotation.copyFrom(this.rotation);
  15250. }
  15251. // Translation
  15252. var camera = this.getScene().activeCamera;
  15253. if (this.infiniteDistance && !this.parent && camera) {
  15254. var cameraWorldMatrix = camera.getWorldMatrix();
  15255. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15256. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15257. }
  15258. else {
  15259. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15260. }
  15261. // Composing transformations
  15262. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15263. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15264. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15265. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15266. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15267. // Need to decompose each rotation here
  15268. var currentPosition = BABYLON.Tmp.Vector3[3];
  15269. if (this.parent && this.parent.getWorldMatrix) {
  15270. if (this._transformToBoneReferal) {
  15271. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15272. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15273. }
  15274. else {
  15275. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15276. }
  15277. }
  15278. else {
  15279. currentPosition.copyFrom(this.position);
  15280. }
  15281. currentPosition.subtractInPlace(camera.globalPosition);
  15282. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15283. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15284. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15285. }
  15286. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15287. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15288. }
  15289. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15290. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15291. }
  15292. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15293. }
  15294. else {
  15295. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15296. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15297. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15298. }
  15299. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15300. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15301. }
  15302. // Local world
  15303. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15304. // Parent
  15305. if (this.parent && this.parent.getWorldMatrix) {
  15306. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15307. if (this._transformToBoneReferal) {
  15308. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15309. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15310. }
  15311. else {
  15312. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15313. }
  15314. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15315. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15316. this._worldMatrix.copyFrom(this._localWorld);
  15317. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15318. }
  15319. else {
  15320. if (this._transformToBoneReferal) {
  15321. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15322. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15323. }
  15324. else {
  15325. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15326. }
  15327. }
  15328. this._markSyncedWithParent();
  15329. }
  15330. else {
  15331. this._worldMatrix.copyFrom(this._localWorld);
  15332. }
  15333. // Post multiply inverse of pivotMatrix
  15334. if (this._postMultiplyPivotMatrix) {
  15335. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15336. }
  15337. // Normal matrix
  15338. if (this.scaling.isNonUniform) {
  15339. this._updateNonUniformScalingState(true);
  15340. }
  15341. else if (this.parent && this.parent._nonUniformScaling) {
  15342. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15343. }
  15344. else {
  15345. this._updateNonUniformScalingState(false);
  15346. }
  15347. this._afterComputeWorldMatrix();
  15348. // Absolute position
  15349. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15350. // Callbacks
  15351. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15352. if (!this._poseMatrix) {
  15353. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15354. }
  15355. // Cache the determinant
  15356. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15357. return this._worldMatrix;
  15358. };
  15359. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15360. };
  15361. /**
  15362. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15363. * @param func: callback function to add
  15364. *
  15365. * Returns the TransformNode.
  15366. */
  15367. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15368. this.onAfterWorldMatrixUpdateObservable.add(func);
  15369. return this;
  15370. };
  15371. /**
  15372. * Removes a registered callback function.
  15373. * Returns the TransformNode.
  15374. */
  15375. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15376. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15377. return this;
  15378. };
  15379. /**
  15380. * Clone the current transform node
  15381. * Returns the new transform node
  15382. * @param name Name of the new clone
  15383. * @param newParent New parent for the clone
  15384. * @param doNotCloneChildren Do not clone children hierarchy
  15385. */
  15386. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15387. var _this = this;
  15388. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15389. result.name = name;
  15390. result.id = name;
  15391. if (newParent) {
  15392. result.parent = newParent;
  15393. }
  15394. if (!doNotCloneChildren) {
  15395. // Children
  15396. var directDescendants = this.getDescendants(true);
  15397. for (var index = 0; index < directDescendants.length; index++) {
  15398. var child = directDescendants[index];
  15399. if (child.clone) {
  15400. child.clone(name + "." + child.name, result);
  15401. }
  15402. }
  15403. }
  15404. return result;
  15405. };
  15406. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15407. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15408. serializationObject.type = this.getClassName();
  15409. // Parent
  15410. if (this.parent) {
  15411. serializationObject.parentId = this.parent.id;
  15412. }
  15413. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15414. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15415. }
  15416. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15417. serializationObject.isEnabled = this.isEnabled();
  15418. // Parent
  15419. if (this.parent) {
  15420. serializationObject.parentId = this.parent.id;
  15421. }
  15422. return serializationObject;
  15423. };
  15424. // Statics
  15425. /**
  15426. * Returns a new TransformNode object parsed from the source provided.
  15427. * The parameter `parsedMesh` is the source.
  15428. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15429. */
  15430. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15431. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15432. if (BABYLON.Tags) {
  15433. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15434. }
  15435. if (parsedTransformNode.localMatrix) {
  15436. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15437. }
  15438. else if (parsedTransformNode.pivotMatrix) {
  15439. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15440. }
  15441. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15442. // Parent
  15443. if (parsedTransformNode.parentId) {
  15444. transformNode._waitingParentId = parsedTransformNode.parentId;
  15445. }
  15446. return transformNode;
  15447. };
  15448. /**
  15449. * Disposes the TransformNode.
  15450. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15451. * Returns nothing.
  15452. */
  15453. TransformNode.prototype.dispose = function (doNotRecurse) {
  15454. // Animations
  15455. this.getScene().stopAnimation(this);
  15456. // Remove from scene
  15457. this.getScene().removeTransformNode(this);
  15458. if (!doNotRecurse) {
  15459. // Children
  15460. var objects = this.getDescendants(true);
  15461. for (var index = 0; index < objects.length; index++) {
  15462. objects[index].dispose();
  15463. }
  15464. }
  15465. else {
  15466. var childMeshes = this.getChildMeshes(true);
  15467. for (index = 0; index < childMeshes.length; index++) {
  15468. var child = childMeshes[index];
  15469. child.parent = null;
  15470. child.computeWorldMatrix(true);
  15471. }
  15472. }
  15473. this.onAfterWorldMatrixUpdateObservable.clear();
  15474. _super.prototype.dispose.call(this);
  15475. };
  15476. // Statics
  15477. TransformNode.BILLBOARDMODE_NONE = 0;
  15478. TransformNode.BILLBOARDMODE_X = 1;
  15479. TransformNode.BILLBOARDMODE_Y = 2;
  15480. TransformNode.BILLBOARDMODE_Z = 4;
  15481. TransformNode.BILLBOARDMODE_ALL = 7;
  15482. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15483. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15484. __decorate([
  15485. BABYLON.serializeAsVector3()
  15486. ], TransformNode.prototype, "_rotation", void 0);
  15487. __decorate([
  15488. BABYLON.serializeAsQuaternion()
  15489. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15490. __decorate([
  15491. BABYLON.serializeAsVector3()
  15492. ], TransformNode.prototype, "_scaling", void 0);
  15493. __decorate([
  15494. BABYLON.serialize()
  15495. ], TransformNode.prototype, "billboardMode", void 0);
  15496. __decorate([
  15497. BABYLON.serialize()
  15498. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15499. __decorate([
  15500. BABYLON.serialize()
  15501. ], TransformNode.prototype, "infiniteDistance", void 0);
  15502. __decorate([
  15503. BABYLON.serializeAsVector3()
  15504. ], TransformNode.prototype, "position", void 0);
  15505. return TransformNode;
  15506. }(BABYLON.Node));
  15507. BABYLON.TransformNode = TransformNode;
  15508. })(BABYLON || (BABYLON = {}));
  15509. //# sourceMappingURL=babylon.transformNode.js.map
  15510. var BABYLON;
  15511. (function (BABYLON) {
  15512. var AbstractMesh = /** @class */ (function (_super) {
  15513. __extends(AbstractMesh, _super);
  15514. // Constructor
  15515. function AbstractMesh(name, scene) {
  15516. if (scene === void 0) { scene = null; }
  15517. var _this = _super.call(this, name, scene, false) || this;
  15518. _this._facetNb = 0; // facet number
  15519. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15520. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15521. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15522. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15523. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15524. _this._subDiv = {
  15525. max: 1,
  15526. X: 1,
  15527. Y: 1,
  15528. Z: 1
  15529. };
  15530. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15531. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15532. // Events
  15533. /**
  15534. * An event triggered when this mesh collides with another one
  15535. * @type {BABYLON.Observable}
  15536. */
  15537. _this.onCollideObservable = new BABYLON.Observable();
  15538. /**
  15539. * An event triggered when the collision's position changes
  15540. * @type {BABYLON.Observable}
  15541. */
  15542. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15543. /**
  15544. * An event triggered when material is changed
  15545. * @type {BABYLON.Observable}
  15546. */
  15547. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15548. // Properties
  15549. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15550. /**
  15551. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15552. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15553. * or
  15554. * 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.
  15555. * for more info check WebGl documentations
  15556. */
  15557. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15558. /**
  15559. * 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:
  15560. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15561. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15562. * 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.
  15563. */
  15564. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15565. /**
  15566. * 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.
  15567. * The default value is -1 which means don't break the query and wait till the result.
  15568. */
  15569. _this.occlusionRetryCount = -1;
  15570. _this._occlusionInternalRetryCounter = 0;
  15571. _this._isOccluded = false;
  15572. _this._isOcclusionQueryInProgress = false;
  15573. _this.visibility = 1.0;
  15574. _this.alphaIndex = Number.MAX_VALUE;
  15575. _this.isVisible = true;
  15576. _this.isPickable = true;
  15577. _this.showBoundingBox = false;
  15578. _this.showSubMeshesBoundingBox = false;
  15579. _this.isBlocker = false;
  15580. _this.enablePointerMoveEvents = false;
  15581. _this.renderingGroupId = 0;
  15582. _this._receiveShadows = false;
  15583. _this.renderOutline = false;
  15584. _this.outlineColor = BABYLON.Color3.Red();
  15585. _this.outlineWidth = 0.02;
  15586. _this.renderOverlay = false;
  15587. _this.overlayColor = BABYLON.Color3.Red();
  15588. _this.overlayAlpha = 0.5;
  15589. _this._hasVertexAlpha = false;
  15590. _this._useVertexColors = true;
  15591. _this._computeBonesUsingShaders = true;
  15592. _this._numBoneInfluencers = 4;
  15593. _this._applyFog = true;
  15594. _this.useOctreeForRenderingSelection = true;
  15595. _this.useOctreeForPicking = true;
  15596. _this.useOctreeForCollisions = true;
  15597. _this._layerMask = 0x0FFFFFFF;
  15598. /**
  15599. * True if the mesh must be rendered in any case.
  15600. */
  15601. _this.alwaysSelectAsActiveMesh = false;
  15602. /**
  15603. * This scene's action manager
  15604. * @type {BABYLON.ActionManager}
  15605. */
  15606. _this.actionManager = null;
  15607. // Physics
  15608. _this.physicsImpostor = null;
  15609. // Collisions
  15610. _this._checkCollisions = false;
  15611. _this._collisionMask = -1;
  15612. _this._collisionGroup = -1;
  15613. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15614. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15615. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15616. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15617. // Edges
  15618. _this.edgesWidth = 1;
  15619. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15620. // Cache
  15621. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15622. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15623. _this._isDisposed = false;
  15624. _this._renderId = 0;
  15625. _this._intersectionsInProgress = new Array();
  15626. _this._unIndexed = false;
  15627. _this._lightSources = new Array();
  15628. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15629. if (collidedMesh === void 0) { collidedMesh = null; }
  15630. //TODO move this to the collision coordinator!
  15631. if (_this.getScene().workerCollisions)
  15632. newPosition.multiplyInPlace(_this._collider._radius);
  15633. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15634. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15635. _this.position.addInPlace(_this._diffPositionForCollisions);
  15636. }
  15637. if (collidedMesh) {
  15638. _this.onCollideObservable.notifyObservers(collidedMesh);
  15639. }
  15640. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15641. };
  15642. _this.getScene().addMesh(_this);
  15643. _this._resyncLightSources();
  15644. return _this;
  15645. }
  15646. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15647. get: function () {
  15648. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15649. },
  15650. enumerable: true,
  15651. configurable: true
  15652. });
  15653. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15654. get: function () {
  15655. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15656. },
  15657. enumerable: true,
  15658. configurable: true
  15659. });
  15660. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15661. get: function () {
  15662. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15663. },
  15664. enumerable: true,
  15665. configurable: true
  15666. });
  15667. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15668. get: function () {
  15669. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15670. },
  15671. enumerable: true,
  15672. configurable: true
  15673. });
  15674. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15675. get: function () {
  15676. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15677. },
  15678. enumerable: true,
  15679. configurable: true
  15680. });
  15681. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15682. /**
  15683. * Read-only : the number of facets in the mesh
  15684. */
  15685. get: function () {
  15686. return this._facetNb;
  15687. },
  15688. enumerable: true,
  15689. configurable: true
  15690. });
  15691. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15692. /**
  15693. * The number (integer) of subdivisions per axis in the partioning space
  15694. */
  15695. get: function () {
  15696. return this._partitioningSubdivisions;
  15697. },
  15698. set: function (nb) {
  15699. this._partitioningSubdivisions = nb;
  15700. },
  15701. enumerable: true,
  15702. configurable: true
  15703. });
  15704. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15705. /**
  15706. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15707. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15708. */
  15709. get: function () {
  15710. return this._partitioningBBoxRatio;
  15711. },
  15712. set: function (ratio) {
  15713. this._partitioningBBoxRatio = ratio;
  15714. },
  15715. enumerable: true,
  15716. configurable: true
  15717. });
  15718. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15719. /**
  15720. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15721. * Works only for updatable meshes.
  15722. * Doesn't work with multi-materials.
  15723. */
  15724. get: function () {
  15725. return this._facetDepthSort;
  15726. },
  15727. set: function (sort) {
  15728. this._facetDepthSort = sort;
  15729. },
  15730. enumerable: true,
  15731. configurable: true
  15732. });
  15733. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15734. /**
  15735. * The location (Vector3) where the facet depth sort must be computed from.
  15736. * By default, the active camera position.
  15737. * Used only when facet depth sort is enabled.
  15738. */
  15739. get: function () {
  15740. return this._facetDepthSortFrom;
  15741. },
  15742. set: function (location) {
  15743. this._facetDepthSortFrom = location;
  15744. },
  15745. enumerable: true,
  15746. configurable: true
  15747. });
  15748. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15749. /**
  15750. * Read-only boolean : is the feature facetData enabled ?
  15751. */
  15752. get: function () {
  15753. return this._facetDataEnabled;
  15754. },
  15755. enumerable: true,
  15756. configurable: true
  15757. });
  15758. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15759. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15760. return false;
  15761. }
  15762. this._markSubMeshesAsMiscDirty();
  15763. return true;
  15764. };
  15765. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15766. set: function (callback) {
  15767. if (this._onCollideObserver) {
  15768. this.onCollideObservable.remove(this._onCollideObserver);
  15769. }
  15770. this._onCollideObserver = this.onCollideObservable.add(callback);
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15776. set: function (callback) {
  15777. if (this._onCollisionPositionChangeObserver) {
  15778. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15779. }
  15780. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15786. /**
  15787. * 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.
  15788. */
  15789. get: function () {
  15790. return this._isOccluded;
  15791. },
  15792. set: function (value) {
  15793. this._isOccluded = value;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15799. /**
  15800. * Flag to check the progress status of the query
  15801. */
  15802. get: function () {
  15803. return this._isOcclusionQueryInProgress;
  15804. },
  15805. enumerable: true,
  15806. configurable: true
  15807. });
  15808. Object.defineProperty(AbstractMesh.prototype, "material", {
  15809. get: function () {
  15810. return this._material;
  15811. },
  15812. set: function (value) {
  15813. if (this._material === value) {
  15814. return;
  15815. }
  15816. this._material = value;
  15817. if (this.onMaterialChangedObservable.hasObservers) {
  15818. this.onMaterialChangedObservable.notifyObservers(this);
  15819. }
  15820. if (!this.subMeshes) {
  15821. return;
  15822. }
  15823. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15824. var subMesh = _a[_i];
  15825. subMesh.setEffect(null);
  15826. }
  15827. },
  15828. enumerable: true,
  15829. configurable: true
  15830. });
  15831. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15832. get: function () {
  15833. return this._receiveShadows;
  15834. },
  15835. set: function (value) {
  15836. if (this._receiveShadows === value) {
  15837. return;
  15838. }
  15839. this._receiveShadows = value;
  15840. this._markSubMeshesAsLightDirty();
  15841. },
  15842. enumerable: true,
  15843. configurable: true
  15844. });
  15845. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15846. get: function () {
  15847. return this._hasVertexAlpha;
  15848. },
  15849. set: function (value) {
  15850. if (this._hasVertexAlpha === value) {
  15851. return;
  15852. }
  15853. this._hasVertexAlpha = value;
  15854. this._markSubMeshesAsAttributesDirty();
  15855. },
  15856. enumerable: true,
  15857. configurable: true
  15858. });
  15859. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15860. get: function () {
  15861. return this._useVertexColors;
  15862. },
  15863. set: function (value) {
  15864. if (this._useVertexColors === value) {
  15865. return;
  15866. }
  15867. this._useVertexColors = value;
  15868. this._markSubMeshesAsAttributesDirty();
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15874. get: function () {
  15875. return this._computeBonesUsingShaders;
  15876. },
  15877. set: function (value) {
  15878. if (this._computeBonesUsingShaders === value) {
  15879. return;
  15880. }
  15881. this._computeBonesUsingShaders = value;
  15882. this._markSubMeshesAsAttributesDirty();
  15883. },
  15884. enumerable: true,
  15885. configurable: true
  15886. });
  15887. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15888. get: function () {
  15889. return this._numBoneInfluencers;
  15890. },
  15891. set: function (value) {
  15892. if (this._numBoneInfluencers === value) {
  15893. return;
  15894. }
  15895. this._numBoneInfluencers = value;
  15896. this._markSubMeshesAsAttributesDirty();
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15902. get: function () {
  15903. return this._applyFog;
  15904. },
  15905. set: function (value) {
  15906. if (this._applyFog === value) {
  15907. return;
  15908. }
  15909. this._applyFog = value;
  15910. this._markSubMeshesAsMiscDirty();
  15911. },
  15912. enumerable: true,
  15913. configurable: true
  15914. });
  15915. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15916. get: function () {
  15917. return this._layerMask;
  15918. },
  15919. set: function (value) {
  15920. if (value === this._layerMask) {
  15921. return;
  15922. }
  15923. this._layerMask = value;
  15924. this._resyncLightSources();
  15925. },
  15926. enumerable: true,
  15927. configurable: true
  15928. });
  15929. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15930. get: function () {
  15931. return this._collisionMask;
  15932. },
  15933. set: function (mask) {
  15934. this._collisionMask = !isNaN(mask) ? mask : -1;
  15935. },
  15936. enumerable: true,
  15937. configurable: true
  15938. });
  15939. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15940. get: function () {
  15941. return this._collisionGroup;
  15942. },
  15943. set: function (mask) {
  15944. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15945. },
  15946. enumerable: true,
  15947. configurable: true
  15948. });
  15949. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15950. get: function () {
  15951. return null;
  15952. },
  15953. enumerable: true,
  15954. configurable: true
  15955. });
  15956. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15957. get: function () {
  15958. return this._skeleton;
  15959. },
  15960. set: function (value) {
  15961. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15962. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15963. }
  15964. if (value && value.needInitialSkinMatrix) {
  15965. value._registerMeshWithPoseMatrix(this);
  15966. }
  15967. this._skeleton = value;
  15968. if (!this._skeleton) {
  15969. this._bonesTransformMatrices = null;
  15970. }
  15971. this._markSubMeshesAsAttributesDirty();
  15972. },
  15973. enumerable: true,
  15974. configurable: true
  15975. });
  15976. /**
  15977. * Boolean : true if the mesh has been disposed.
  15978. */
  15979. AbstractMesh.prototype.isDisposed = function () {
  15980. return this._isDisposed;
  15981. };
  15982. /**
  15983. * Returns the string "AbstractMesh"
  15984. */
  15985. AbstractMesh.prototype.getClassName = function () {
  15986. return "AbstractMesh";
  15987. };
  15988. /**
  15989. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15990. */
  15991. AbstractMesh.prototype.toString = function (fullDetails) {
  15992. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15993. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15994. if (this._skeleton) {
  15995. ret += ", skeleton: " + this._skeleton.name;
  15996. }
  15997. if (fullDetails) {
  15998. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15999. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16000. }
  16001. return ret;
  16002. };
  16003. AbstractMesh.prototype._rebuild = function () {
  16004. if (this._occlusionQuery) {
  16005. this._occlusionQuery = null;
  16006. }
  16007. if (this._edgesRenderer) {
  16008. this._edgesRenderer._rebuild();
  16009. }
  16010. if (!this.subMeshes) {
  16011. return;
  16012. }
  16013. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16014. var subMesh = _a[_i];
  16015. subMesh._rebuild();
  16016. }
  16017. };
  16018. AbstractMesh.prototype._resyncLightSources = function () {
  16019. this._lightSources.length = 0;
  16020. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16021. var light = _a[_i];
  16022. if (!light.isEnabled()) {
  16023. continue;
  16024. }
  16025. if (light.canAffectMesh(this)) {
  16026. this._lightSources.push(light);
  16027. }
  16028. }
  16029. this._markSubMeshesAsLightDirty();
  16030. };
  16031. AbstractMesh.prototype._resyncLighSource = function (light) {
  16032. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16033. var index = this._lightSources.indexOf(light);
  16034. if (index === -1) {
  16035. if (!isIn) {
  16036. return;
  16037. }
  16038. this._lightSources.push(light);
  16039. }
  16040. else {
  16041. if (isIn) {
  16042. return;
  16043. }
  16044. this._lightSources.splice(index, 1);
  16045. }
  16046. this._markSubMeshesAsLightDirty();
  16047. };
  16048. AbstractMesh.prototype._removeLightSource = function (light) {
  16049. var index = this._lightSources.indexOf(light);
  16050. if (index === -1) {
  16051. return;
  16052. }
  16053. this._lightSources.splice(index, 1);
  16054. this._markSubMeshesAsLightDirty();
  16055. };
  16056. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16057. if (!this.subMeshes) {
  16058. return;
  16059. }
  16060. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16061. var subMesh = _a[_i];
  16062. if (subMesh._materialDefines) {
  16063. func(subMesh._materialDefines);
  16064. }
  16065. }
  16066. };
  16067. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16068. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16069. };
  16070. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16071. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16072. };
  16073. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16074. if (!this.subMeshes) {
  16075. return;
  16076. }
  16077. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16078. var subMesh = _a[_i];
  16079. var material = subMesh.getMaterial();
  16080. if (material) {
  16081. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16082. }
  16083. }
  16084. };
  16085. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16086. /**
  16087. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16088. * Default : (1.0, 1.0, 1.0)
  16089. */
  16090. get: function () {
  16091. return this._scaling;
  16092. },
  16093. /**
  16094. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16095. * Default : (1.0, 1.0, 1.0)
  16096. */
  16097. set: function (newScaling) {
  16098. this._scaling = newScaling;
  16099. if (this.physicsImpostor) {
  16100. this.physicsImpostor.forceUpdate();
  16101. }
  16102. },
  16103. enumerable: true,
  16104. configurable: true
  16105. });
  16106. // Methods
  16107. /**
  16108. * Disables the mesh edger rendering mode.
  16109. * Returns the AbstractMesh.
  16110. */
  16111. AbstractMesh.prototype.disableEdgesRendering = function () {
  16112. if (this._edgesRenderer) {
  16113. this._edgesRenderer.dispose();
  16114. this._edgesRenderer = null;
  16115. }
  16116. return this;
  16117. };
  16118. /**
  16119. * Enables the edge rendering mode on the mesh.
  16120. * This mode makes the mesh edges visible.
  16121. * Returns the AbstractMesh.
  16122. */
  16123. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16124. if (epsilon === void 0) { epsilon = 0.95; }
  16125. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16126. this.disableEdgesRendering();
  16127. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16128. return this;
  16129. };
  16130. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16131. /**
  16132. * Returns true if the mesh is blocked. Used by the class Mesh.
  16133. * Returns the boolean `false` by default.
  16134. */
  16135. get: function () {
  16136. return false;
  16137. },
  16138. enumerable: true,
  16139. configurable: true
  16140. });
  16141. /**
  16142. * Returns the mesh itself by default, used by the class Mesh.
  16143. * Returned type : AbstractMesh
  16144. */
  16145. AbstractMesh.prototype.getLOD = function (camera) {
  16146. return this;
  16147. };
  16148. /**
  16149. * Returns 0 by default, used by the class Mesh.
  16150. * Returns an integer.
  16151. */
  16152. AbstractMesh.prototype.getTotalVertices = function () {
  16153. return 0;
  16154. };
  16155. /**
  16156. * Returns null by default, used by the class Mesh.
  16157. * Returned type : integer array
  16158. */
  16159. AbstractMesh.prototype.getIndices = function () {
  16160. return null;
  16161. };
  16162. /**
  16163. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16164. * Returned type : float array or Float32Array
  16165. */
  16166. AbstractMesh.prototype.getVerticesData = function (kind) {
  16167. return null;
  16168. };
  16169. /**
  16170. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16171. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16172. * The `data` are either a numeric array either a Float32Array.
  16173. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16174. * 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).
  16175. * Note that a new underlying VertexBuffer object is created each call.
  16176. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16177. *
  16178. * Possible `kind` values :
  16179. * - BABYLON.VertexBuffer.PositionKind
  16180. * - BABYLON.VertexBuffer.UVKind
  16181. * - BABYLON.VertexBuffer.UV2Kind
  16182. * - BABYLON.VertexBuffer.UV3Kind
  16183. * - BABYLON.VertexBuffer.UV4Kind
  16184. * - BABYLON.VertexBuffer.UV5Kind
  16185. * - BABYLON.VertexBuffer.UV6Kind
  16186. * - BABYLON.VertexBuffer.ColorKind
  16187. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16188. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16189. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16190. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16191. *
  16192. * Returns the Mesh.
  16193. */
  16194. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16195. return this;
  16196. };
  16197. /**
  16198. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16199. * If the mesh has no geometry, it is simply returned as it is.
  16200. * The `data` are either a numeric array either a Float32Array.
  16201. * No new underlying VertexBuffer object is created.
  16202. * 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.
  16203. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16204. *
  16205. * Possible `kind` values :
  16206. * - BABYLON.VertexBuffer.PositionKind
  16207. * - BABYLON.VertexBuffer.UVKind
  16208. * - BABYLON.VertexBuffer.UV2Kind
  16209. * - BABYLON.VertexBuffer.UV3Kind
  16210. * - BABYLON.VertexBuffer.UV4Kind
  16211. * - BABYLON.VertexBuffer.UV5Kind
  16212. * - BABYLON.VertexBuffer.UV6Kind
  16213. * - BABYLON.VertexBuffer.ColorKind
  16214. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16215. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16216. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16217. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16218. *
  16219. * Returns the Mesh.
  16220. */
  16221. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16222. return this;
  16223. };
  16224. /**
  16225. * Sets the mesh indices.
  16226. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16227. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16228. * This method creates a new index buffer each call.
  16229. * Returns the Mesh.
  16230. */
  16231. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16232. return this;
  16233. };
  16234. /** Returns false by default, used by the class Mesh.
  16235. * Returns a boolean
  16236. */
  16237. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16238. return false;
  16239. };
  16240. /**
  16241. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16242. * Returns a BoundingInfo
  16243. */
  16244. AbstractMesh.prototype.getBoundingInfo = function () {
  16245. if (this._masterMesh) {
  16246. return this._masterMesh.getBoundingInfo();
  16247. }
  16248. if (!this._boundingInfo) {
  16249. // this._boundingInfo is being created here
  16250. this._updateBoundingInfo();
  16251. }
  16252. // cannot be null.
  16253. return this._boundingInfo;
  16254. };
  16255. /**
  16256. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16257. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16258. */
  16259. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16260. if (includeDescendants === void 0) { includeDescendants = true; }
  16261. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16262. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16263. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16264. if (maxDimension === 0) {
  16265. return this;
  16266. }
  16267. var scale = 1 / maxDimension;
  16268. this.scaling.scaleInPlace(scale);
  16269. return this;
  16270. };
  16271. /**
  16272. * Sets a mesh new object BoundingInfo.
  16273. * Returns the AbstractMesh.
  16274. */
  16275. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16276. this._boundingInfo = boundingInfo;
  16277. return this;
  16278. };
  16279. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16280. get: function () {
  16281. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16282. },
  16283. enumerable: true,
  16284. configurable: true
  16285. });
  16286. AbstractMesh.prototype._preActivate = function () {
  16287. };
  16288. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16289. };
  16290. AbstractMesh.prototype._activate = function (renderId) {
  16291. this._renderId = renderId;
  16292. };
  16293. /**
  16294. * Returns the latest update of the World matrix
  16295. * Returns a Matrix.
  16296. */
  16297. AbstractMesh.prototype.getWorldMatrix = function () {
  16298. if (this._masterMesh) {
  16299. return this._masterMesh.getWorldMatrix();
  16300. }
  16301. return _super.prototype.getWorldMatrix.call(this);
  16302. };
  16303. /**
  16304. * Returns the latest update of the World matrix determinant.
  16305. */
  16306. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16307. if (this._masterMesh) {
  16308. return this._masterMesh._getWorldMatrixDeterminant();
  16309. }
  16310. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16311. };
  16312. // ================================== Point of View Movement =================================
  16313. /**
  16314. * Perform relative position change from the point of view of behind the front of the mesh.
  16315. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16316. * Supports definition of mesh facing forward or backward.
  16317. * @param {number} amountRight
  16318. * @param {number} amountUp
  16319. * @param {number} amountForward
  16320. *
  16321. * Returns the AbstractMesh.
  16322. */
  16323. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16324. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16325. return this;
  16326. };
  16327. /**
  16328. * Calculate relative position change from the point of view of behind the front of the mesh.
  16329. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16330. * Supports definition of mesh facing forward or backward.
  16331. * @param {number} amountRight
  16332. * @param {number} amountUp
  16333. * @param {number} amountForward
  16334. *
  16335. * Returns a new Vector3.
  16336. */
  16337. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16338. var rotMatrix = new BABYLON.Matrix();
  16339. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16340. rotQuaternion.toRotationMatrix(rotMatrix);
  16341. var translationDelta = BABYLON.Vector3.Zero();
  16342. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16343. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16344. return translationDelta;
  16345. };
  16346. // ================================== Point of View Rotation =================================
  16347. /**
  16348. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16349. * Supports definition of mesh facing forward or backward.
  16350. * @param {number} flipBack
  16351. * @param {number} twirlClockwise
  16352. * @param {number} tiltRight
  16353. *
  16354. * Returns the AbstractMesh.
  16355. */
  16356. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16357. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16358. return this;
  16359. };
  16360. /**
  16361. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16362. * Supports definition of mesh facing forward or backward.
  16363. * @param {number} flipBack
  16364. * @param {number} twirlClockwise
  16365. * @param {number} tiltRight
  16366. *
  16367. * Returns a new Vector3.
  16368. */
  16369. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16370. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16371. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16372. };
  16373. /**
  16374. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16375. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16376. */
  16377. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16378. if (includeDescendants === void 0) { includeDescendants = true; }
  16379. this.computeWorldMatrix(true);
  16380. var min;
  16381. var max;
  16382. var boundingInfo = this.getBoundingInfo();
  16383. if (!this.subMeshes) {
  16384. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16385. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16386. }
  16387. else {
  16388. min = boundingInfo.boundingBox.minimumWorld;
  16389. max = boundingInfo.boundingBox.maximumWorld;
  16390. }
  16391. if (includeDescendants) {
  16392. var descendants = this.getDescendants(false);
  16393. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16394. var descendant = descendants_1[_i];
  16395. var childMesh = descendant;
  16396. childMesh.computeWorldMatrix(true);
  16397. //make sure we have the needed params to get mix and max
  16398. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16399. continue;
  16400. }
  16401. var childBoundingInfo = childMesh.getBoundingInfo();
  16402. var boundingBox = childBoundingInfo.boundingBox;
  16403. var minBox = boundingBox.minimumWorld;
  16404. var maxBox = boundingBox.maximumWorld;
  16405. BABYLON.Tools.CheckExtends(minBox, min, max);
  16406. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16407. }
  16408. }
  16409. return {
  16410. min: min,
  16411. max: max
  16412. };
  16413. };
  16414. /**
  16415. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16416. * Returns the AbstractMesh.
  16417. */
  16418. AbstractMesh.prototype._updateBoundingInfo = function () {
  16419. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16420. this._boundingInfo.update(this.worldMatrixFromCache);
  16421. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16422. return this;
  16423. };
  16424. /**
  16425. * Update a mesh's children BoundingInfo objects only.
  16426. * Returns the AbstractMesh.
  16427. */
  16428. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16429. if (!this.subMeshes) {
  16430. return this;
  16431. }
  16432. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16433. var subMesh = this.subMeshes[subIndex];
  16434. if (!subMesh.IsGlobal) {
  16435. subMesh.updateBoundingInfo(matrix);
  16436. }
  16437. }
  16438. return this;
  16439. };
  16440. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16441. // Bounding info
  16442. this._updateBoundingInfo();
  16443. };
  16444. /**
  16445. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16446. * A mesh is in the frustum if its bounding box intersects the frustum.
  16447. * Boolean returned.
  16448. */
  16449. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16450. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16451. };
  16452. /**
  16453. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16454. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16455. * Boolean returned.
  16456. */
  16457. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16458. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16459. ;
  16460. };
  16461. /**
  16462. * True if the mesh intersects another mesh or a SolidParticle object.
  16463. * 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)
  16464. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16465. * Returns a boolean.
  16466. */
  16467. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16468. if (precise === void 0) { precise = false; }
  16469. if (!this._boundingInfo || !mesh._boundingInfo) {
  16470. return false;
  16471. }
  16472. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16473. return true;
  16474. }
  16475. if (includeDescendants) {
  16476. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16477. var child = _a[_i];
  16478. if (child.intersectsMesh(mesh, precise, true)) {
  16479. return true;
  16480. }
  16481. }
  16482. }
  16483. return false;
  16484. };
  16485. /**
  16486. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16487. * Returns a boolean.
  16488. */
  16489. AbstractMesh.prototype.intersectsPoint = function (point) {
  16490. if (!this._boundingInfo) {
  16491. return false;
  16492. }
  16493. return this._boundingInfo.intersectsPoint(point);
  16494. };
  16495. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16496. return this.physicsImpostor;
  16497. };
  16498. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16499. if (camera === void 0) { camera = null; }
  16500. if (!camera) {
  16501. camera = this.getScene().activeCamera;
  16502. }
  16503. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16504. };
  16505. /**
  16506. * Returns the distance from the mesh to the active camera.
  16507. * Returns a float.
  16508. */
  16509. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16510. if (camera === void 0) { camera = null; }
  16511. if (!camera) {
  16512. camera = this.getScene().activeCamera;
  16513. }
  16514. return this.absolutePosition.subtract(camera.position).length();
  16515. };
  16516. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16517. if (!this.physicsImpostor) {
  16518. return this;
  16519. }
  16520. this.physicsImpostor.applyImpulse(force, contactPoint);
  16521. return this;
  16522. };
  16523. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16524. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16525. return this;
  16526. }
  16527. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16528. mainPivot: pivot1,
  16529. connectedPivot: pivot2,
  16530. nativeParams: options
  16531. });
  16532. return this;
  16533. };
  16534. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16535. // Collisions
  16536. /**
  16537. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16538. * Default `false`.
  16539. */
  16540. get: function () {
  16541. return this._checkCollisions;
  16542. },
  16543. set: function (collisionEnabled) {
  16544. this._checkCollisions = collisionEnabled;
  16545. if (this.getScene().workerCollisions) {
  16546. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16547. }
  16548. },
  16549. enumerable: true,
  16550. configurable: true
  16551. });
  16552. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16553. /**
  16554. * Gets Collider object used to compute collisions (not physics)
  16555. */
  16556. get: function () {
  16557. return this._collider;
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16563. var globalPosition = this.getAbsolutePosition();
  16564. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16565. if (!this._collider) {
  16566. this._collider = new BABYLON.Collider();
  16567. }
  16568. this._collider._radius = this.ellipsoid;
  16569. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16570. return this;
  16571. };
  16572. // Submeshes octree
  16573. /**
  16574. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16575. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16576. * Returns an Octree of submeshes.
  16577. */
  16578. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16579. if (maxCapacity === void 0) { maxCapacity = 64; }
  16580. if (maxDepth === void 0) { maxDepth = 2; }
  16581. if (!this._submeshesOctree) {
  16582. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16583. }
  16584. this.computeWorldMatrix(true);
  16585. var boundingInfo = this.getBoundingInfo();
  16586. // Update octree
  16587. var bbox = boundingInfo.boundingBox;
  16588. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16589. return this._submeshesOctree;
  16590. };
  16591. // Collisions
  16592. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16593. this._generatePointsArray();
  16594. if (!this._positions) {
  16595. return this;
  16596. }
  16597. // Transformation
  16598. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16599. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16600. subMesh._lastColliderWorldVertices = [];
  16601. subMesh._trianglePlanes = [];
  16602. var start = subMesh.verticesStart;
  16603. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16604. for (var i = start; i < end; i++) {
  16605. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16606. }
  16607. }
  16608. // Collide
  16609. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16610. if (collider.collisionFound) {
  16611. collider.collidedMesh = this;
  16612. }
  16613. return this;
  16614. };
  16615. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16616. var subMeshes;
  16617. var len;
  16618. // Octrees
  16619. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16620. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16621. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16622. len = intersections.length;
  16623. subMeshes = intersections.data;
  16624. }
  16625. else {
  16626. subMeshes = this.subMeshes;
  16627. len = subMeshes.length;
  16628. }
  16629. for (var index = 0; index < len; index++) {
  16630. var subMesh = subMeshes[index];
  16631. // Bounding test
  16632. if (len > 1 && !subMesh._checkCollision(collider))
  16633. continue;
  16634. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16635. }
  16636. return this;
  16637. };
  16638. AbstractMesh.prototype._checkCollision = function (collider) {
  16639. // Bounding box test
  16640. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16641. return this;
  16642. // Transformation matrix
  16643. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16644. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16645. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16646. return this;
  16647. };
  16648. // Picking
  16649. AbstractMesh.prototype._generatePointsArray = function () {
  16650. return false;
  16651. };
  16652. /**
  16653. * Checks if the passed Ray intersects with the mesh.
  16654. * Returns an object PickingInfo.
  16655. */
  16656. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16657. var pickingInfo = new BABYLON.PickingInfo();
  16658. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16659. return pickingInfo;
  16660. }
  16661. if (!this._generatePointsArray()) {
  16662. return pickingInfo;
  16663. }
  16664. var intersectInfo = null;
  16665. // Octrees
  16666. var subMeshes;
  16667. var len;
  16668. if (this._submeshesOctree && this.useOctreeForPicking) {
  16669. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16670. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16671. len = intersections.length;
  16672. subMeshes = intersections.data;
  16673. }
  16674. else {
  16675. subMeshes = this.subMeshes;
  16676. len = subMeshes.length;
  16677. }
  16678. for (var index = 0; index < len; index++) {
  16679. var subMesh = subMeshes[index];
  16680. // Bounding test
  16681. if (len > 1 && !subMesh.canIntersects(ray))
  16682. continue;
  16683. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16684. if (currentIntersectInfo) {
  16685. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16686. intersectInfo = currentIntersectInfo;
  16687. intersectInfo.subMeshId = index;
  16688. if (fastCheck) {
  16689. break;
  16690. }
  16691. }
  16692. }
  16693. }
  16694. if (intersectInfo) {
  16695. // Get picked point
  16696. var world = this.getWorldMatrix();
  16697. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16698. var direction = ray.direction.clone();
  16699. direction = direction.scale(intersectInfo.distance);
  16700. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16701. var pickedPoint = worldOrigin.add(worldDirection);
  16702. // Return result
  16703. pickingInfo.hit = true;
  16704. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16705. pickingInfo.pickedPoint = pickedPoint;
  16706. pickingInfo.pickedMesh = this;
  16707. pickingInfo.bu = intersectInfo.bu || 0;
  16708. pickingInfo.bv = intersectInfo.bv || 0;
  16709. pickingInfo.faceId = intersectInfo.faceId;
  16710. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16711. return pickingInfo;
  16712. }
  16713. return pickingInfo;
  16714. };
  16715. /**
  16716. * Clones the mesh, used by the class Mesh.
  16717. * Just returns `null` for an AbstractMesh.
  16718. */
  16719. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16720. return null;
  16721. };
  16722. /**
  16723. * Disposes all the mesh submeshes.
  16724. * Returns the AbstractMesh.
  16725. */
  16726. AbstractMesh.prototype.releaseSubMeshes = function () {
  16727. if (this.subMeshes) {
  16728. while (this.subMeshes.length) {
  16729. this.subMeshes[0].dispose();
  16730. }
  16731. }
  16732. else {
  16733. this.subMeshes = new Array();
  16734. }
  16735. return this;
  16736. };
  16737. /**
  16738. * Disposes the AbstractMesh.
  16739. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16740. * Returns nothing.
  16741. */
  16742. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16743. var _this = this;
  16744. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16745. var index;
  16746. // Action manager
  16747. if (this.actionManager !== undefined && this.actionManager !== null) {
  16748. this.actionManager.dispose();
  16749. this.actionManager = null;
  16750. }
  16751. // Skeleton
  16752. this.skeleton = null;
  16753. // Physics
  16754. if (this.physicsImpostor) {
  16755. this.physicsImpostor.dispose();
  16756. }
  16757. // Intersections in progress
  16758. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16759. var other = this._intersectionsInProgress[index];
  16760. var pos = other._intersectionsInProgress.indexOf(this);
  16761. other._intersectionsInProgress.splice(pos, 1);
  16762. }
  16763. this._intersectionsInProgress = [];
  16764. // Lights
  16765. var lights = this.getScene().lights;
  16766. lights.forEach(function (light) {
  16767. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16768. if (meshIndex !== -1) {
  16769. light.includedOnlyMeshes.splice(meshIndex, 1);
  16770. }
  16771. meshIndex = light.excludedMeshes.indexOf(_this);
  16772. if (meshIndex !== -1) {
  16773. light.excludedMeshes.splice(meshIndex, 1);
  16774. }
  16775. // Shadow generators
  16776. var generator = light.getShadowGenerator();
  16777. if (generator) {
  16778. var shadowMap = generator.getShadowMap();
  16779. if (shadowMap && shadowMap.renderList) {
  16780. meshIndex = shadowMap.renderList.indexOf(_this);
  16781. if (meshIndex !== -1) {
  16782. shadowMap.renderList.splice(meshIndex, 1);
  16783. }
  16784. }
  16785. }
  16786. });
  16787. // Edges
  16788. if (this._edgesRenderer) {
  16789. this._edgesRenderer.dispose();
  16790. this._edgesRenderer = null;
  16791. }
  16792. // SubMeshes
  16793. if (this.getClassName() !== "InstancedMesh") {
  16794. this.releaseSubMeshes();
  16795. }
  16796. // Octree
  16797. var sceneOctree = this.getScene().selectionOctree;
  16798. if (sceneOctree !== undefined && sceneOctree !== null) {
  16799. var index = sceneOctree.dynamicContent.indexOf(this);
  16800. if (index !== -1) {
  16801. sceneOctree.dynamicContent.splice(index, 1);
  16802. }
  16803. }
  16804. // Query
  16805. var engine = this.getScene().getEngine();
  16806. if (this._occlusionQuery) {
  16807. this._isOcclusionQueryInProgress = false;
  16808. engine.deleteQuery(this._occlusionQuery);
  16809. this._occlusionQuery = null;
  16810. }
  16811. // Engine
  16812. engine.wipeCaches();
  16813. // Remove from scene
  16814. this.getScene().removeMesh(this);
  16815. if (disposeMaterialAndTextures) {
  16816. if (this.material) {
  16817. this.material.dispose(false, true);
  16818. }
  16819. }
  16820. if (!doNotRecurse) {
  16821. // Particles
  16822. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16823. if (this.getScene().particleSystems[index].emitter === this) {
  16824. this.getScene().particleSystems[index].dispose();
  16825. index--;
  16826. }
  16827. }
  16828. }
  16829. // facet data
  16830. if (this._facetDataEnabled) {
  16831. this.disableFacetData();
  16832. }
  16833. this.onAfterWorldMatrixUpdateObservable.clear();
  16834. this.onCollideObservable.clear();
  16835. this.onCollisionPositionChangeObservable.clear();
  16836. this._isDisposed = true;
  16837. _super.prototype.dispose.call(this, doNotRecurse);
  16838. };
  16839. /**
  16840. * Adds the passed mesh as a child to the current mesh.
  16841. * Returns the AbstractMesh.
  16842. */
  16843. AbstractMesh.prototype.addChild = function (mesh) {
  16844. mesh.setParent(this);
  16845. return this;
  16846. };
  16847. /**
  16848. * Removes the passed mesh from the current mesh children list.
  16849. * Returns the AbstractMesh.
  16850. */
  16851. AbstractMesh.prototype.removeChild = function (mesh) {
  16852. mesh.setParent(null);
  16853. return this;
  16854. };
  16855. // Facet data
  16856. /**
  16857. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16858. * Returns the AbstractMesh.
  16859. */
  16860. AbstractMesh.prototype._initFacetData = function () {
  16861. if (!this._facetNormals) {
  16862. this._facetNormals = new Array();
  16863. }
  16864. if (!this._facetPositions) {
  16865. this._facetPositions = new Array();
  16866. }
  16867. if (!this._facetPartitioning) {
  16868. this._facetPartitioning = new Array();
  16869. }
  16870. this._facetNb = (this.getIndices().length / 3) | 0;
  16871. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16872. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16873. for (var f = 0; f < this._facetNb; f++) {
  16874. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16875. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16876. }
  16877. this._facetDataEnabled = true;
  16878. return this;
  16879. };
  16880. /**
  16881. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16882. * This method can be called within the render loop.
  16883. * 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.
  16884. * Returns the AbstractMesh.
  16885. */
  16886. AbstractMesh.prototype.updateFacetData = function () {
  16887. if (!this._facetDataEnabled) {
  16888. this._initFacetData();
  16889. }
  16890. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16891. var indices = this.getIndices();
  16892. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16893. var bInfo = this.getBoundingInfo();
  16894. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16895. // init arrays, matrix and sort function on first call
  16896. this._facetDepthSortEnabled = true;
  16897. if (indices instanceof Uint16Array) {
  16898. this._depthSortedIndices = new Uint16Array(indices);
  16899. }
  16900. else if (indices instanceof Uint32Array) {
  16901. this._depthSortedIndices = new Uint32Array(indices);
  16902. }
  16903. else {
  16904. var needs32bits = false;
  16905. for (var i = 0; i < indices.length; i++) {
  16906. if (indices[i] > 65535) {
  16907. needs32bits = true;
  16908. break;
  16909. }
  16910. }
  16911. if (needs32bits) {
  16912. this._depthSortedIndices = new Uint32Array(indices);
  16913. }
  16914. else {
  16915. this._depthSortedIndices = new Uint16Array(indices);
  16916. }
  16917. }
  16918. this._facetDepthSortFunction = function (f1, f2) {
  16919. return (f2.sqDistance - f1.sqDistance);
  16920. };
  16921. if (!this._facetDepthSortFrom) {
  16922. var camera = this.getScene().activeCamera;
  16923. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16924. }
  16925. this._depthSortedFacets = [];
  16926. for (var f = 0; f < this._facetNb; f++) {
  16927. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16928. this._depthSortedFacets.push(depthSortedFacet);
  16929. }
  16930. this._invertedMatrix = BABYLON.Matrix.Identity();
  16931. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16932. }
  16933. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16934. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16935. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16936. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16937. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16938. this._subDiv.max = this._partitioningSubdivisions;
  16939. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16940. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16941. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16942. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16943. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16944. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16945. // set the parameters for ComputeNormals()
  16946. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16947. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16948. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16949. this._facetParameters.bInfo = bInfo;
  16950. this._facetParameters.bbSize = this._bbSize;
  16951. this._facetParameters.subDiv = this._subDiv;
  16952. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16953. this._facetParameters.depthSort = this._facetDepthSort;
  16954. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16955. this.computeWorldMatrix(true);
  16956. this._worldMatrix.invertToRef(this._invertedMatrix);
  16957. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16958. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16959. }
  16960. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16961. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16962. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16963. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16964. var l = (this._depthSortedIndices.length / 3) | 0;
  16965. for (var f = 0; f < l; f++) {
  16966. var sind = this._depthSortedFacets[f].ind;
  16967. this._depthSortedIndices[f * 3] = indices[sind];
  16968. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16969. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16970. }
  16971. this.updateIndices(this._depthSortedIndices);
  16972. }
  16973. return this;
  16974. };
  16975. /**
  16976. * Returns the facetLocalNormals array.
  16977. * The normals are expressed in the mesh local space.
  16978. */
  16979. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16980. if (!this._facetNormals) {
  16981. this.updateFacetData();
  16982. }
  16983. return this._facetNormals;
  16984. };
  16985. /**
  16986. * Returns the facetLocalPositions array.
  16987. * The facet positions are expressed in the mesh local space.
  16988. */
  16989. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16990. if (!this._facetPositions) {
  16991. this.updateFacetData();
  16992. }
  16993. return this._facetPositions;
  16994. };
  16995. /**
  16996. * Returns the facetLocalPartioning array.
  16997. */
  16998. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16999. if (!this._facetPartitioning) {
  17000. this.updateFacetData();
  17001. }
  17002. return this._facetPartitioning;
  17003. };
  17004. /**
  17005. * Returns the i-th facet position in the world system.
  17006. * This method allocates a new Vector3 per call.
  17007. */
  17008. AbstractMesh.prototype.getFacetPosition = function (i) {
  17009. var pos = BABYLON.Vector3.Zero();
  17010. this.getFacetPositionToRef(i, pos);
  17011. return pos;
  17012. };
  17013. /**
  17014. * Sets the reference Vector3 with the i-th facet position in the world system.
  17015. * Returns the AbstractMesh.
  17016. */
  17017. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17018. var localPos = (this.getFacetLocalPositions())[i];
  17019. var world = this.getWorldMatrix();
  17020. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17021. return this;
  17022. };
  17023. /**
  17024. * Returns the i-th facet normal in the world system.
  17025. * This method allocates a new Vector3 per call.
  17026. */
  17027. AbstractMesh.prototype.getFacetNormal = function (i) {
  17028. var norm = BABYLON.Vector3.Zero();
  17029. this.getFacetNormalToRef(i, norm);
  17030. return norm;
  17031. };
  17032. /**
  17033. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17034. * Returns the AbstractMesh.
  17035. */
  17036. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17037. var localNorm = (this.getFacetLocalNormals())[i];
  17038. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17039. return this;
  17040. };
  17041. /**
  17042. * 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).
  17043. */
  17044. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17045. var bInfo = this.getBoundingInfo();
  17046. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17047. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17048. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17049. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17050. return null;
  17051. }
  17052. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17053. };
  17054. /**
  17055. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17056. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17057. * 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.
  17058. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17059. * 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.
  17060. */
  17061. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17062. if (checkFace === void 0) { checkFace = false; }
  17063. if (facing === void 0) { facing = true; }
  17064. var world = this.getWorldMatrix();
  17065. var invMat = BABYLON.Tmp.Matrix[5];
  17066. world.invertToRef(invMat);
  17067. var invVect = BABYLON.Tmp.Vector3[8];
  17068. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17069. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17070. if (projected) {
  17071. // tranform the local computed projected vector to world coordinates
  17072. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17073. }
  17074. return closest;
  17075. };
  17076. /**
  17077. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17078. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17079. * 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.
  17080. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17081. * 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.
  17082. */
  17083. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17084. if (checkFace === void 0) { checkFace = false; }
  17085. if (facing === void 0) { facing = true; }
  17086. var closest = null;
  17087. var tmpx = 0.0;
  17088. var tmpy = 0.0;
  17089. var tmpz = 0.0;
  17090. var d = 0.0; // tmp dot facet normal * facet position
  17091. var t0 = 0.0;
  17092. var projx = 0.0;
  17093. var projy = 0.0;
  17094. var projz = 0.0;
  17095. // Get all the facets in the same partitioning block than (x, y, z)
  17096. var facetPositions = this.getFacetLocalPositions();
  17097. var facetNormals = this.getFacetLocalNormals();
  17098. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17099. if (!facetsInBlock) {
  17100. return null;
  17101. }
  17102. // Get the closest facet to (x, y, z)
  17103. var shortest = Number.MAX_VALUE; // init distance vars
  17104. var tmpDistance = shortest;
  17105. var fib; // current facet in the block
  17106. var norm; // current facet normal
  17107. var p0; // current facet barycenter position
  17108. // loop on all the facets in the current partitioning block
  17109. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17110. fib = facetsInBlock[idx];
  17111. norm = facetNormals[fib];
  17112. p0 = facetPositions[fib];
  17113. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17114. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17115. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17116. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17117. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17118. projx = x + norm.x * t0;
  17119. projy = y + norm.y * t0;
  17120. projz = z + norm.z * t0;
  17121. tmpx = projx - x;
  17122. tmpy = projy - y;
  17123. tmpz = projz - z;
  17124. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17125. if (tmpDistance < shortest) {
  17126. shortest = tmpDistance;
  17127. closest = fib;
  17128. if (projected) {
  17129. projected.x = projx;
  17130. projected.y = projy;
  17131. projected.z = projz;
  17132. }
  17133. }
  17134. }
  17135. }
  17136. return closest;
  17137. };
  17138. /**
  17139. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17140. */
  17141. AbstractMesh.prototype.getFacetDataParameters = function () {
  17142. return this._facetParameters;
  17143. };
  17144. /**
  17145. * Disables the feature FacetData and frees the related memory.
  17146. * Returns the AbstractMesh.
  17147. */
  17148. AbstractMesh.prototype.disableFacetData = function () {
  17149. if (this._facetDataEnabled) {
  17150. this._facetDataEnabled = false;
  17151. this._facetPositions = new Array();
  17152. this._facetNormals = new Array();
  17153. this._facetPartitioning = new Array();
  17154. this._facetParameters = null;
  17155. this._depthSortedIndices = new Uint32Array(0);
  17156. }
  17157. return this;
  17158. };
  17159. /**
  17160. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17161. * Returns the mesh.
  17162. */
  17163. AbstractMesh.prototype.updateIndices = function (indices) {
  17164. return this;
  17165. };
  17166. /**
  17167. * The mesh Geometry. Actually used by the Mesh object.
  17168. * Returns a blank geometry object.
  17169. */
  17170. /**
  17171. * Creates new normals data for the mesh.
  17172. * @param updatable.
  17173. */
  17174. AbstractMesh.prototype.createNormals = function (updatable) {
  17175. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17176. var indices = this.getIndices();
  17177. var normals;
  17178. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17179. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17180. }
  17181. else {
  17182. normals = [];
  17183. }
  17184. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17185. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17186. };
  17187. /**
  17188. * Align the mesh with a normal.
  17189. * Returns the mesh.
  17190. */
  17191. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17192. if (!upDirection) {
  17193. upDirection = BABYLON.Axis.Y;
  17194. }
  17195. var axisX = BABYLON.Tmp.Vector3[0];
  17196. var axisZ = BABYLON.Tmp.Vector3[1];
  17197. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17198. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17199. if (this.rotationQuaternion) {
  17200. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17201. }
  17202. else {
  17203. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17204. }
  17205. return this;
  17206. };
  17207. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17208. var engine = this.getEngine();
  17209. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17210. this._isOccluded = false;
  17211. return;
  17212. }
  17213. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17214. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17215. if (isOcclusionQueryAvailable) {
  17216. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17217. this._isOcclusionQueryInProgress = false;
  17218. this._occlusionInternalRetryCounter = 0;
  17219. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17220. }
  17221. else {
  17222. this._occlusionInternalRetryCounter++;
  17223. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17224. this._isOcclusionQueryInProgress = false;
  17225. this._occlusionInternalRetryCounter = 0;
  17226. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17227. // if strict continue the last state of the object.
  17228. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17229. }
  17230. else {
  17231. return;
  17232. }
  17233. }
  17234. }
  17235. var scene = this.getScene();
  17236. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17237. if (!this._occlusionQuery) {
  17238. this._occlusionQuery = engine.createQuery();
  17239. }
  17240. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17241. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17242. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17243. this._isOcclusionQueryInProgress = true;
  17244. };
  17245. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17246. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17247. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17248. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17249. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17250. return AbstractMesh;
  17251. }(BABYLON.TransformNode));
  17252. BABYLON.AbstractMesh = AbstractMesh;
  17253. })(BABYLON || (BABYLON = {}));
  17254. //# sourceMappingURL=babylon.abstractMesh.js.map
  17255. var BABYLON;
  17256. (function (BABYLON) {
  17257. var Light = /** @class */ (function (_super) {
  17258. __extends(Light, _super);
  17259. /**
  17260. * Creates a Light object in the scene.
  17261. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17262. */
  17263. function Light(name, scene) {
  17264. var _this = _super.call(this, name, scene) || this;
  17265. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17266. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17267. _this.intensity = 1.0;
  17268. _this.range = Number.MAX_VALUE;
  17269. /**
  17270. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17271. * of light.
  17272. */
  17273. _this._photometricScale = 1.0;
  17274. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17275. _this._radius = 0.00001;
  17276. _this.renderPriority = 0;
  17277. /**
  17278. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17279. * the current shadow generator.
  17280. */
  17281. _this.shadowEnabled = true;
  17282. _this._excludeWithLayerMask = 0;
  17283. _this._includeOnlyWithLayerMask = 0;
  17284. _this._lightmapMode = 0;
  17285. _this._excludedMeshesIds = new Array();
  17286. _this._includedOnlyMeshesIds = new Array();
  17287. _this.getScene().addLight(_this);
  17288. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17289. _this._buildUniformLayout();
  17290. _this.includedOnlyMeshes = new Array();
  17291. _this.excludedMeshes = new Array();
  17292. _this._resyncMeshes();
  17293. return _this;
  17294. }
  17295. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17296. /**
  17297. * If every light affecting the material is in this lightmapMode,
  17298. * material.lightmapTexture adds or multiplies
  17299. * (depends on material.useLightmapAsShadowmap)
  17300. * after every other light calculations.
  17301. */
  17302. get: function () {
  17303. return Light._LIGHTMAP_DEFAULT;
  17304. },
  17305. enumerable: true,
  17306. configurable: true
  17307. });
  17308. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17309. /**
  17310. * material.lightmapTexture as only diffuse lighting from this light
  17311. * adds only specular lighting from this light
  17312. * adds dynamic shadows
  17313. */
  17314. get: function () {
  17315. return Light._LIGHTMAP_SPECULAR;
  17316. },
  17317. enumerable: true,
  17318. configurable: true
  17319. });
  17320. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17321. /**
  17322. * material.lightmapTexture as only lighting
  17323. * no light calculation from this light
  17324. * only adds dynamic shadows from this light
  17325. */
  17326. get: function () {
  17327. return Light._LIGHTMAP_SHADOWSONLY;
  17328. },
  17329. enumerable: true,
  17330. configurable: true
  17331. });
  17332. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17333. /**
  17334. * Each light type uses the default quantity according to its type:
  17335. * point/spot lights use luminous intensity
  17336. * directional lights use illuminance
  17337. */
  17338. get: function () {
  17339. return Light._INTENSITYMODE_AUTOMATIC;
  17340. },
  17341. enumerable: true,
  17342. configurable: true
  17343. });
  17344. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17345. /**
  17346. * lumen (lm)
  17347. */
  17348. get: function () {
  17349. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17350. },
  17351. enumerable: true,
  17352. configurable: true
  17353. });
  17354. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17355. /**
  17356. * candela (lm/sr)
  17357. */
  17358. get: function () {
  17359. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17360. },
  17361. enumerable: true,
  17362. configurable: true
  17363. });
  17364. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17365. /**
  17366. * lux (lm/m^2)
  17367. */
  17368. get: function () {
  17369. return Light._INTENSITYMODE_ILLUMINANCE;
  17370. },
  17371. enumerable: true,
  17372. configurable: true
  17373. });
  17374. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17375. /**
  17376. * nit (cd/m^2)
  17377. */
  17378. get: function () {
  17379. return Light._INTENSITYMODE_LUMINANCE;
  17380. },
  17381. enumerable: true,
  17382. configurable: true
  17383. });
  17384. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17385. /**
  17386. * Light type const id of the point light.
  17387. */
  17388. get: function () {
  17389. return Light._LIGHTTYPEID_POINTLIGHT;
  17390. },
  17391. enumerable: true,
  17392. configurable: true
  17393. });
  17394. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17395. /**
  17396. * Light type const id of the directional light.
  17397. */
  17398. get: function () {
  17399. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17400. },
  17401. enumerable: true,
  17402. configurable: true
  17403. });
  17404. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17405. /**
  17406. * Light type const id of the spot light.
  17407. */
  17408. get: function () {
  17409. return Light._LIGHTTYPEID_SPOTLIGHT;
  17410. },
  17411. enumerable: true,
  17412. configurable: true
  17413. });
  17414. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17415. /**
  17416. * Light type const id of the hemispheric light.
  17417. */
  17418. get: function () {
  17419. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17420. },
  17421. enumerable: true,
  17422. configurable: true
  17423. });
  17424. Object.defineProperty(Light.prototype, "intensityMode", {
  17425. /**
  17426. * Gets the photometric scale used to interpret the intensity.
  17427. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17428. */
  17429. get: function () {
  17430. return this._intensityMode;
  17431. },
  17432. /**
  17433. * Sets the photometric scale used to interpret the intensity.
  17434. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17435. */
  17436. set: function (value) {
  17437. this._intensityMode = value;
  17438. this._computePhotometricScale();
  17439. },
  17440. enumerable: true,
  17441. configurable: true
  17442. });
  17443. ;
  17444. ;
  17445. Object.defineProperty(Light.prototype, "radius", {
  17446. /**
  17447. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17448. */
  17449. get: function () {
  17450. return this._radius;
  17451. },
  17452. /**
  17453. * sets the light radius used by PBR Materials to simulate soft area lights.
  17454. */
  17455. set: function (value) {
  17456. this._radius = value;
  17457. this._computePhotometricScale();
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. ;
  17463. ;
  17464. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17465. get: function () {
  17466. return this._includedOnlyMeshes;
  17467. },
  17468. set: function (value) {
  17469. this._includedOnlyMeshes = value;
  17470. this._hookArrayForIncludedOnly(value);
  17471. },
  17472. enumerable: true,
  17473. configurable: true
  17474. });
  17475. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17476. get: function () {
  17477. return this._excludedMeshes;
  17478. },
  17479. set: function (value) {
  17480. this._excludedMeshes = value;
  17481. this._hookArrayForExcluded(value);
  17482. },
  17483. enumerable: true,
  17484. configurable: true
  17485. });
  17486. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17487. get: function () {
  17488. return this._excludeWithLayerMask;
  17489. },
  17490. set: function (value) {
  17491. this._excludeWithLayerMask = value;
  17492. this._resyncMeshes();
  17493. },
  17494. enumerable: true,
  17495. configurable: true
  17496. });
  17497. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17498. get: function () {
  17499. return this._includeOnlyWithLayerMask;
  17500. },
  17501. set: function (value) {
  17502. this._includeOnlyWithLayerMask = value;
  17503. this._resyncMeshes();
  17504. },
  17505. enumerable: true,
  17506. configurable: true
  17507. });
  17508. Object.defineProperty(Light.prototype, "lightmapMode", {
  17509. get: function () {
  17510. return this._lightmapMode;
  17511. },
  17512. set: function (value) {
  17513. if (this._lightmapMode === value) {
  17514. return;
  17515. }
  17516. this._lightmapMode = value;
  17517. this._markMeshesAsLightDirty();
  17518. },
  17519. enumerable: true,
  17520. configurable: true
  17521. });
  17522. Light.prototype._buildUniformLayout = function () {
  17523. // Overridden
  17524. };
  17525. /**
  17526. * Returns the string "Light".
  17527. */
  17528. Light.prototype.getClassName = function () {
  17529. return "Light";
  17530. };
  17531. /**
  17532. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17533. */
  17534. Light.prototype.toString = function (fullDetails) {
  17535. var ret = "Name: " + this.name;
  17536. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17537. if (this.animations) {
  17538. for (var i = 0; i < this.animations.length; i++) {
  17539. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17540. }
  17541. }
  17542. if (fullDetails) {
  17543. }
  17544. return ret;
  17545. };
  17546. /**
  17547. * Set the enabled state of this node.
  17548. * @param {boolean} value - the new enabled state
  17549. * @see isEnabled
  17550. */
  17551. Light.prototype.setEnabled = function (value) {
  17552. _super.prototype.setEnabled.call(this, value);
  17553. this._resyncMeshes();
  17554. };
  17555. /**
  17556. * Returns the Light associated shadow generator.
  17557. */
  17558. Light.prototype.getShadowGenerator = function () {
  17559. return this._shadowGenerator;
  17560. };
  17561. /**
  17562. * Returns a Vector3, the absolute light position in the World.
  17563. */
  17564. Light.prototype.getAbsolutePosition = function () {
  17565. return BABYLON.Vector3.Zero();
  17566. };
  17567. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17568. };
  17569. Light.prototype._getWorldMatrix = function () {
  17570. return BABYLON.Matrix.Identity();
  17571. };
  17572. /**
  17573. * Boolean : True if the light will affect the passed mesh.
  17574. */
  17575. Light.prototype.canAffectMesh = function (mesh) {
  17576. if (!mesh) {
  17577. return true;
  17578. }
  17579. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17580. return false;
  17581. }
  17582. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17583. return false;
  17584. }
  17585. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17586. return false;
  17587. }
  17588. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17589. return false;
  17590. }
  17591. return true;
  17592. };
  17593. /**
  17594. * Returns the light World matrix.
  17595. */
  17596. Light.prototype.getWorldMatrix = function () {
  17597. this._currentRenderId = this.getScene().getRenderId();
  17598. var worldMatrix = this._getWorldMatrix();
  17599. if (this.parent && this.parent.getWorldMatrix) {
  17600. if (!this._parentedWorldMatrix) {
  17601. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17602. }
  17603. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17604. this._markSyncedWithParent();
  17605. return this._parentedWorldMatrix;
  17606. }
  17607. return worldMatrix;
  17608. };
  17609. /**
  17610. * Sort function to order lights for rendering.
  17611. * @param a First Light object to compare to second.
  17612. * @param b Second Light object to compare first.
  17613. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17614. */
  17615. Light.compareLightsPriority = function (a, b) {
  17616. //shadow-casting lights have priority over non-shadow-casting lights
  17617. //the renderPrioirty is a secondary sort criterion
  17618. if (a.shadowEnabled !== b.shadowEnabled) {
  17619. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17620. }
  17621. return b.renderPriority - a.renderPriority;
  17622. };
  17623. /**
  17624. * Disposes the light.
  17625. */
  17626. Light.prototype.dispose = function () {
  17627. if (this._shadowGenerator) {
  17628. this._shadowGenerator.dispose();
  17629. this._shadowGenerator = null;
  17630. }
  17631. // Animations
  17632. this.getScene().stopAnimation(this);
  17633. this._uniformBuffer.dispose();
  17634. // Remove from scene
  17635. this.getScene().removeLight(this);
  17636. _super.prototype.dispose.call(this);
  17637. };
  17638. /**
  17639. * Returns the light type ID (integer).
  17640. */
  17641. Light.prototype.getTypeID = function () {
  17642. return 0;
  17643. };
  17644. /**
  17645. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17646. */
  17647. Light.prototype.getScaledIntensity = function () {
  17648. return this._photometricScale * this.intensity;
  17649. };
  17650. /**
  17651. * Returns a new Light object, named "name", from the current one.
  17652. */
  17653. Light.prototype.clone = function (name) {
  17654. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17655. if (!constructor) {
  17656. return null;
  17657. }
  17658. return BABYLON.SerializationHelper.Clone(constructor, this);
  17659. };
  17660. /**
  17661. * Serializes the current light into a Serialization object.
  17662. * Returns the serialized object.
  17663. */
  17664. Light.prototype.serialize = function () {
  17665. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17666. // Type
  17667. serializationObject.type = this.getTypeID();
  17668. // Parent
  17669. if (this.parent) {
  17670. serializationObject.parentId = this.parent.id;
  17671. }
  17672. // Inclusion / exclusions
  17673. if (this.excludedMeshes.length > 0) {
  17674. serializationObject.excludedMeshesIds = [];
  17675. this.excludedMeshes.forEach(function (mesh) {
  17676. serializationObject.excludedMeshesIds.push(mesh.id);
  17677. });
  17678. }
  17679. if (this.includedOnlyMeshes.length > 0) {
  17680. serializationObject.includedOnlyMeshesIds = [];
  17681. this.includedOnlyMeshes.forEach(function (mesh) {
  17682. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17683. });
  17684. }
  17685. // Animations
  17686. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17687. serializationObject.ranges = this.serializeAnimationRanges();
  17688. return serializationObject;
  17689. };
  17690. /**
  17691. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17692. * This new light is named "name" and added to the passed scene.
  17693. */
  17694. Light.GetConstructorFromName = function (type, name, scene) {
  17695. switch (type) {
  17696. case 0:
  17697. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17698. case 1:
  17699. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17700. case 2:
  17701. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17702. case 3:
  17703. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17704. }
  17705. return null;
  17706. };
  17707. /**
  17708. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17709. */
  17710. Light.Parse = function (parsedLight, scene) {
  17711. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17712. if (!constructor) {
  17713. return null;
  17714. }
  17715. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17716. // Inclusion / exclusions
  17717. if (parsedLight.excludedMeshesIds) {
  17718. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17719. }
  17720. if (parsedLight.includedOnlyMeshesIds) {
  17721. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17722. }
  17723. // Parent
  17724. if (parsedLight.parentId) {
  17725. light._waitingParentId = parsedLight.parentId;
  17726. }
  17727. // Animations
  17728. if (parsedLight.animations) {
  17729. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17730. var parsedAnimation = parsedLight.animations[animationIndex];
  17731. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17732. }
  17733. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17734. }
  17735. if (parsedLight.autoAnimate) {
  17736. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17737. }
  17738. return light;
  17739. };
  17740. Light.prototype._hookArrayForExcluded = function (array) {
  17741. var _this = this;
  17742. var oldPush = array.push;
  17743. array.push = function () {
  17744. var items = [];
  17745. for (var _i = 0; _i < arguments.length; _i++) {
  17746. items[_i] = arguments[_i];
  17747. }
  17748. var result = oldPush.apply(array, items);
  17749. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17750. var item = items_1[_a];
  17751. item._resyncLighSource(_this);
  17752. }
  17753. return result;
  17754. };
  17755. var oldSplice = array.splice;
  17756. array.splice = function (index, deleteCount) {
  17757. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17758. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17759. var item = deleted_1[_i];
  17760. item._resyncLighSource(_this);
  17761. }
  17762. return deleted;
  17763. };
  17764. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17765. var item = array_1[_i];
  17766. item._resyncLighSource(this);
  17767. }
  17768. };
  17769. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17770. var _this = this;
  17771. var oldPush = array.push;
  17772. array.push = function () {
  17773. var items = [];
  17774. for (var _i = 0; _i < arguments.length; _i++) {
  17775. items[_i] = arguments[_i];
  17776. }
  17777. var result = oldPush.apply(array, items);
  17778. _this._resyncMeshes();
  17779. return result;
  17780. };
  17781. var oldSplice = array.splice;
  17782. array.splice = function (index, deleteCount) {
  17783. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17784. _this._resyncMeshes();
  17785. return deleted;
  17786. };
  17787. this._resyncMeshes();
  17788. };
  17789. Light.prototype._resyncMeshes = function () {
  17790. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17791. var mesh = _a[_i];
  17792. mesh._resyncLighSource(this);
  17793. }
  17794. };
  17795. Light.prototype._markMeshesAsLightDirty = function () {
  17796. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17797. var mesh = _a[_i];
  17798. if (mesh._lightSources.indexOf(this) !== -1) {
  17799. mesh._markSubMeshesAsLightDirty();
  17800. }
  17801. }
  17802. };
  17803. /**
  17804. * Recomputes the cached photometric scale if needed.
  17805. */
  17806. Light.prototype._computePhotometricScale = function () {
  17807. this._photometricScale = this._getPhotometricScale();
  17808. this.getScene().resetCachedMaterial();
  17809. };
  17810. /**
  17811. * Returns the Photometric Scale according to the light type and intensity mode.
  17812. */
  17813. Light.prototype._getPhotometricScale = function () {
  17814. var photometricScale = 0.0;
  17815. var lightTypeID = this.getTypeID();
  17816. //get photometric mode
  17817. var photometricMode = this.intensityMode;
  17818. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17819. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17820. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17821. }
  17822. else {
  17823. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17824. }
  17825. }
  17826. //compute photometric scale
  17827. switch (lightTypeID) {
  17828. case Light.LIGHTTYPEID_POINTLIGHT:
  17829. case Light.LIGHTTYPEID_SPOTLIGHT:
  17830. switch (photometricMode) {
  17831. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17832. photometricScale = 1.0 / (4.0 * Math.PI);
  17833. break;
  17834. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17835. photometricScale = 1.0;
  17836. break;
  17837. case Light.INTENSITYMODE_LUMINANCE:
  17838. photometricScale = this.radius * this.radius;
  17839. break;
  17840. }
  17841. break;
  17842. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17843. switch (photometricMode) {
  17844. case Light.INTENSITYMODE_ILLUMINANCE:
  17845. photometricScale = 1.0;
  17846. break;
  17847. case Light.INTENSITYMODE_LUMINANCE:
  17848. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17849. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17850. var apexAngleRadians = this.radius;
  17851. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17852. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17853. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17854. photometricScale = solidAngle;
  17855. break;
  17856. }
  17857. break;
  17858. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17859. // No fall off in hemisperic light.
  17860. photometricScale = 1.0;
  17861. break;
  17862. }
  17863. return photometricScale;
  17864. };
  17865. Light.prototype._reorderLightsInScene = function () {
  17866. var scene = this.getScene();
  17867. if (this._renderPriority != 0) {
  17868. scene.requireLightSorting = true;
  17869. }
  17870. this.getScene().sortLightsByPriority();
  17871. };
  17872. //lightmapMode Consts
  17873. Light._LIGHTMAP_DEFAULT = 0;
  17874. Light._LIGHTMAP_SPECULAR = 1;
  17875. Light._LIGHTMAP_SHADOWSONLY = 2;
  17876. // Intensity Mode Consts
  17877. Light._INTENSITYMODE_AUTOMATIC = 0;
  17878. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17879. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17880. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17881. Light._INTENSITYMODE_LUMINANCE = 4;
  17882. // Light types ids const.
  17883. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17884. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17885. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17886. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17887. __decorate([
  17888. BABYLON.serializeAsColor3()
  17889. ], Light.prototype, "diffuse", void 0);
  17890. __decorate([
  17891. BABYLON.serializeAsColor3()
  17892. ], Light.prototype, "specular", void 0);
  17893. __decorate([
  17894. BABYLON.serialize()
  17895. ], Light.prototype, "intensity", void 0);
  17896. __decorate([
  17897. BABYLON.serialize()
  17898. ], Light.prototype, "range", void 0);
  17899. __decorate([
  17900. BABYLON.serialize()
  17901. ], Light.prototype, "intensityMode", null);
  17902. __decorate([
  17903. BABYLON.serialize()
  17904. ], Light.prototype, "radius", null);
  17905. __decorate([
  17906. BABYLON.serialize()
  17907. ], Light.prototype, "_renderPriority", void 0);
  17908. __decorate([
  17909. BABYLON.expandToProperty("_reorderLightsInScene")
  17910. ], Light.prototype, "renderPriority", void 0);
  17911. __decorate([
  17912. BABYLON.serialize()
  17913. ], Light.prototype, "shadowEnabled", void 0);
  17914. __decorate([
  17915. BABYLON.serialize("excludeWithLayerMask")
  17916. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17917. __decorate([
  17918. BABYLON.serialize("includeOnlyWithLayerMask")
  17919. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17920. __decorate([
  17921. BABYLON.serialize("lightmapMode")
  17922. ], Light.prototype, "_lightmapMode", void 0);
  17923. return Light;
  17924. }(BABYLON.Node));
  17925. BABYLON.Light = Light;
  17926. })(BABYLON || (BABYLON = {}));
  17927. //# sourceMappingURL=babylon.light.js.map
  17928. var BABYLON;
  17929. (function (BABYLON) {
  17930. var Camera = /** @class */ (function (_super) {
  17931. __extends(Camera, _super);
  17932. function Camera(name, position, scene) {
  17933. var _this = _super.call(this, name, scene) || this;
  17934. /**
  17935. * The vector the camera should consider as up.
  17936. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  17937. */
  17938. _this.upVector = BABYLON.Vector3.Up();
  17939. _this.orthoLeft = null;
  17940. _this.orthoRight = null;
  17941. _this.orthoBottom = null;
  17942. _this.orthoTop = null;
  17943. /**
  17944. * FOV is set in Radians. (default is 0.8)
  17945. */
  17946. _this.fov = 0.8;
  17947. _this.minZ = 1;
  17948. _this.maxZ = 10000.0;
  17949. _this.inertia = 0.9;
  17950. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17951. _this.isIntermediate = false;
  17952. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17953. /**
  17954. * Restricts the camera to viewing objects with the same layerMask.
  17955. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  17956. */
  17957. _this.layerMask = 0x0FFFFFFF;
  17958. /**
  17959. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  17960. */
  17961. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17962. // Camera rig members
  17963. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17964. _this._rigCameras = new Array();
  17965. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17966. _this._skipRendering = false;
  17967. _this.customRenderTargets = new Array();
  17968. // Observables
  17969. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17970. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17971. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17972. _this.onRestoreStateObservable = new BABYLON.Observable();
  17973. // Cache
  17974. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17975. _this._projectionMatrix = new BABYLON.Matrix();
  17976. _this._doNotComputeProjectionMatrix = false;
  17977. _this._postProcesses = new Array();
  17978. _this._transformMatrix = BABYLON.Matrix.Zero();
  17979. _this._activeMeshes = new BABYLON.SmartArray(256);
  17980. _this._globalPosition = BABYLON.Vector3.Zero();
  17981. _this._refreshFrustumPlanes = true;
  17982. _this.getScene().addCamera(_this);
  17983. if (!_this.getScene().activeCamera) {
  17984. _this.getScene().activeCamera = _this;
  17985. }
  17986. _this.position = position;
  17987. return _this;
  17988. }
  17989. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17990. get: function () {
  17991. return Camera._PERSPECTIVE_CAMERA;
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17997. get: function () {
  17998. return Camera._ORTHOGRAPHIC_CAMERA;
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18004. /**
  18005. * This is the default FOV mode for perspective cameras.
  18006. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18007. *
  18008. */
  18009. get: function () {
  18010. return Camera._FOVMODE_VERTICAL_FIXED;
  18011. },
  18012. enumerable: true,
  18013. configurable: true
  18014. });
  18015. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18016. /**
  18017. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18018. *
  18019. */
  18020. get: function () {
  18021. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18022. },
  18023. enumerable: true,
  18024. configurable: true
  18025. });
  18026. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18027. get: function () {
  18028. return Camera._RIG_MODE_NONE;
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18034. get: function () {
  18035. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18041. get: function () {
  18042. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18043. },
  18044. enumerable: true,
  18045. configurable: true
  18046. });
  18047. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18048. get: function () {
  18049. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18050. },
  18051. enumerable: true,
  18052. configurable: true
  18053. });
  18054. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18055. get: function () {
  18056. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18057. },
  18058. enumerable: true,
  18059. configurable: true
  18060. });
  18061. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18062. get: function () {
  18063. return Camera._RIG_MODE_VR;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18069. get: function () {
  18070. return Camera._RIG_MODE_WEBVR;
  18071. },
  18072. enumerable: true,
  18073. configurable: true
  18074. });
  18075. /**
  18076. * Store current camera state (fov, position, etc..)
  18077. */
  18078. Camera.prototype.storeState = function () {
  18079. this._stateStored = true;
  18080. this._storedFov = this.fov;
  18081. return this;
  18082. };
  18083. /**
  18084. * Restores the camera state values if it has been stored. You must call storeState() first
  18085. */
  18086. Camera.prototype._restoreStateValues = function () {
  18087. if (!this._stateStored) {
  18088. return false;
  18089. }
  18090. this.fov = this._storedFov;
  18091. return true;
  18092. };
  18093. /**
  18094. * Restored camera state. You must call storeState() first
  18095. */
  18096. Camera.prototype.restoreState = function () {
  18097. if (this._restoreStateValues()) {
  18098. this.onRestoreStateObservable.notifyObservers(this);
  18099. return true;
  18100. }
  18101. return false;
  18102. };
  18103. Camera.prototype.getClassName = function () {
  18104. return "Camera";
  18105. };
  18106. /**
  18107. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18108. */
  18109. Camera.prototype.toString = function (fullDetails) {
  18110. var ret = "Name: " + this.name;
  18111. ret += ", type: " + this.getClassName();
  18112. if (this.animations) {
  18113. for (var i = 0; i < this.animations.length; i++) {
  18114. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18115. }
  18116. }
  18117. if (fullDetails) {
  18118. }
  18119. return ret;
  18120. };
  18121. Object.defineProperty(Camera.prototype, "globalPosition", {
  18122. get: function () {
  18123. return this._globalPosition;
  18124. },
  18125. enumerable: true,
  18126. configurable: true
  18127. });
  18128. Camera.prototype.getActiveMeshes = function () {
  18129. return this._activeMeshes;
  18130. };
  18131. Camera.prototype.isActiveMesh = function (mesh) {
  18132. return (this._activeMeshes.indexOf(mesh) !== -1);
  18133. };
  18134. //Cache
  18135. Camera.prototype._initCache = function () {
  18136. _super.prototype._initCache.call(this);
  18137. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18138. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18139. this._cache.mode = undefined;
  18140. this._cache.minZ = undefined;
  18141. this._cache.maxZ = undefined;
  18142. this._cache.fov = undefined;
  18143. this._cache.fovMode = undefined;
  18144. this._cache.aspectRatio = undefined;
  18145. this._cache.orthoLeft = undefined;
  18146. this._cache.orthoRight = undefined;
  18147. this._cache.orthoBottom = undefined;
  18148. this._cache.orthoTop = undefined;
  18149. this._cache.renderWidth = undefined;
  18150. this._cache.renderHeight = undefined;
  18151. };
  18152. Camera.prototype._updateCache = function (ignoreParentClass) {
  18153. if (!ignoreParentClass) {
  18154. _super.prototype._updateCache.call(this);
  18155. }
  18156. this._cache.position.copyFrom(this.position);
  18157. this._cache.upVector.copyFrom(this.upVector);
  18158. };
  18159. // Synchronized
  18160. Camera.prototype._isSynchronized = function () {
  18161. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18162. };
  18163. Camera.prototype._isSynchronizedViewMatrix = function () {
  18164. if (!_super.prototype._isSynchronized.call(this))
  18165. return false;
  18166. return this._cache.position.equals(this.position)
  18167. && this._cache.upVector.equals(this.upVector)
  18168. && this.isSynchronizedWithParent();
  18169. };
  18170. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18171. var check = this._cache.mode === this.mode
  18172. && this._cache.minZ === this.minZ
  18173. && this._cache.maxZ === this.maxZ;
  18174. if (!check) {
  18175. return false;
  18176. }
  18177. var engine = this.getEngine();
  18178. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18179. check = this._cache.fov === this.fov
  18180. && this._cache.fovMode === this.fovMode
  18181. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18182. }
  18183. else {
  18184. check = this._cache.orthoLeft === this.orthoLeft
  18185. && this._cache.orthoRight === this.orthoRight
  18186. && this._cache.orthoBottom === this.orthoBottom
  18187. && this._cache.orthoTop === this.orthoTop
  18188. && this._cache.renderWidth === engine.getRenderWidth()
  18189. && this._cache.renderHeight === engine.getRenderHeight();
  18190. }
  18191. return check;
  18192. };
  18193. // Controls
  18194. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18195. };
  18196. Camera.prototype.detachControl = function (element) {
  18197. };
  18198. Camera.prototype.update = function () {
  18199. this._checkInputs();
  18200. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18201. this._updateRigCameras();
  18202. }
  18203. };
  18204. Camera.prototype._checkInputs = function () {
  18205. this.onAfterCheckInputsObservable.notifyObservers(this);
  18206. };
  18207. Object.defineProperty(Camera.prototype, "rigCameras", {
  18208. get: function () {
  18209. return this._rigCameras;
  18210. },
  18211. enumerable: true,
  18212. configurable: true
  18213. });
  18214. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18215. get: function () {
  18216. return this._rigPostProcess;
  18217. },
  18218. enumerable: true,
  18219. configurable: true
  18220. });
  18221. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18222. // invalidate framebuffer
  18223. if (this._postProcesses.length > 0) {
  18224. this._postProcesses[0].markTextureDirty();
  18225. }
  18226. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18227. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18228. var cam = this._rigCameras[i];
  18229. var rigPostProcess = cam._rigPostProcess;
  18230. // for VR rig, there does not have to be a post process
  18231. if (rigPostProcess) {
  18232. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18233. if (isPass) {
  18234. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18235. cam.isIntermediate = this._postProcesses.length === 0;
  18236. }
  18237. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18238. rigPostProcess.markTextureDirty();
  18239. }
  18240. else {
  18241. cam._postProcesses = this._postProcesses.slice(0);
  18242. }
  18243. }
  18244. };
  18245. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18246. if (insertAt === void 0) { insertAt = null; }
  18247. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18248. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18249. return 0;
  18250. }
  18251. if (insertAt == null || insertAt < 0) {
  18252. this._postProcesses.push(postProcess);
  18253. }
  18254. else {
  18255. this._postProcesses.splice(insertAt, 0, postProcess);
  18256. }
  18257. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18258. return this._postProcesses.indexOf(postProcess);
  18259. };
  18260. Camera.prototype.detachPostProcess = function (postProcess) {
  18261. var idx = this._postProcesses.indexOf(postProcess);
  18262. if (idx !== -1) {
  18263. this._postProcesses.splice(idx, 1);
  18264. }
  18265. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18266. };
  18267. Camera.prototype.getWorldMatrix = function () {
  18268. if (!this._worldMatrix) {
  18269. this._worldMatrix = BABYLON.Matrix.Identity();
  18270. }
  18271. var viewMatrix = this.getViewMatrix();
  18272. viewMatrix.invertToRef(this._worldMatrix);
  18273. return this._worldMatrix;
  18274. };
  18275. Camera.prototype._getViewMatrix = function () {
  18276. return BABYLON.Matrix.Identity();
  18277. };
  18278. Camera.prototype.getViewMatrix = function (force) {
  18279. if (!force && this._isSynchronizedViewMatrix()) {
  18280. return this._computedViewMatrix;
  18281. }
  18282. this.updateCache();
  18283. this._computedViewMatrix = this._getViewMatrix();
  18284. this._currentRenderId = this.getScene().getRenderId();
  18285. this._refreshFrustumPlanes = true;
  18286. if (!this.parent || !this.parent.getWorldMatrix) {
  18287. this._globalPosition.copyFrom(this.position);
  18288. }
  18289. else {
  18290. if (!this._worldMatrix) {
  18291. this._worldMatrix = BABYLON.Matrix.Identity();
  18292. }
  18293. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18294. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18295. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18296. this._computedViewMatrix.invert();
  18297. this._markSyncedWithParent();
  18298. }
  18299. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18300. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18301. }
  18302. this.onViewMatrixChangedObservable.notifyObservers(this);
  18303. return this._computedViewMatrix;
  18304. };
  18305. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18306. this._doNotComputeProjectionMatrix = true;
  18307. if (projection !== undefined) {
  18308. this._projectionMatrix = projection;
  18309. }
  18310. };
  18311. ;
  18312. Camera.prototype.unfreezeProjectionMatrix = function () {
  18313. this._doNotComputeProjectionMatrix = false;
  18314. };
  18315. ;
  18316. Camera.prototype.getProjectionMatrix = function (force) {
  18317. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18318. return this._projectionMatrix;
  18319. }
  18320. // Cache
  18321. this._cache.mode = this.mode;
  18322. this._cache.minZ = this.minZ;
  18323. this._cache.maxZ = this.maxZ;
  18324. // Matrix
  18325. this._refreshFrustumPlanes = true;
  18326. var engine = this.getEngine();
  18327. var scene = this.getScene();
  18328. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18329. this._cache.fov = this.fov;
  18330. this._cache.fovMode = this.fovMode;
  18331. this._cache.aspectRatio = engine.getAspectRatio(this);
  18332. if (this.minZ <= 0) {
  18333. this.minZ = 0.1;
  18334. }
  18335. if (scene.useRightHandedSystem) {
  18336. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18337. }
  18338. else {
  18339. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18340. }
  18341. }
  18342. else {
  18343. var halfWidth = engine.getRenderWidth() / 2.0;
  18344. var halfHeight = engine.getRenderHeight() / 2.0;
  18345. if (scene.useRightHandedSystem) {
  18346. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18347. }
  18348. else {
  18349. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18350. }
  18351. this._cache.orthoLeft = this.orthoLeft;
  18352. this._cache.orthoRight = this.orthoRight;
  18353. this._cache.orthoBottom = this.orthoBottom;
  18354. this._cache.orthoTop = this.orthoTop;
  18355. this._cache.renderWidth = engine.getRenderWidth();
  18356. this._cache.renderHeight = engine.getRenderHeight();
  18357. }
  18358. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18359. return this._projectionMatrix;
  18360. };
  18361. Camera.prototype.getTranformationMatrix = function () {
  18362. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18363. return this._transformMatrix;
  18364. };
  18365. Camera.prototype.updateFrustumPlanes = function () {
  18366. if (!this._refreshFrustumPlanes) {
  18367. return;
  18368. }
  18369. this.getTranformationMatrix();
  18370. if (!this._frustumPlanes) {
  18371. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18372. }
  18373. else {
  18374. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18375. }
  18376. this._refreshFrustumPlanes = false;
  18377. };
  18378. Camera.prototype.isInFrustum = function (target) {
  18379. this.updateFrustumPlanes();
  18380. return target.isInFrustum(this._frustumPlanes);
  18381. };
  18382. Camera.prototype.isCompletelyInFrustum = function (target) {
  18383. this.updateFrustumPlanes();
  18384. return target.isCompletelyInFrustum(this._frustumPlanes);
  18385. };
  18386. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18387. if (length === void 0) { length = 100; }
  18388. if (!transform) {
  18389. transform = this.getWorldMatrix();
  18390. }
  18391. if (!origin) {
  18392. origin = this.position;
  18393. }
  18394. var forward = new BABYLON.Vector3(0, 0, 1);
  18395. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18396. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18397. return new BABYLON.Ray(origin, direction, length);
  18398. };
  18399. Camera.prototype.dispose = function () {
  18400. // Observables
  18401. this.onViewMatrixChangedObservable.clear();
  18402. this.onProjectionMatrixChangedObservable.clear();
  18403. this.onAfterCheckInputsObservable.clear();
  18404. this.onRestoreStateObservable.clear();
  18405. // Inputs
  18406. if (this.inputs) {
  18407. this.inputs.clear();
  18408. }
  18409. // Animations
  18410. this.getScene().stopAnimation(this);
  18411. // Remove from scene
  18412. this.getScene().removeCamera(this);
  18413. while (this._rigCameras.length > 0) {
  18414. var camera = this._rigCameras.pop();
  18415. if (camera) {
  18416. camera.dispose();
  18417. }
  18418. }
  18419. // Postprocesses
  18420. if (this._rigPostProcess) {
  18421. this._rigPostProcess.dispose(this);
  18422. this._rigPostProcess = null;
  18423. this._postProcesses = [];
  18424. }
  18425. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18426. this._rigPostProcess = null;
  18427. this._postProcesses = [];
  18428. }
  18429. else {
  18430. var i = this._postProcesses.length;
  18431. while (--i >= 0) {
  18432. this._postProcesses[i].dispose(this);
  18433. }
  18434. }
  18435. // Render targets
  18436. var i = this.customRenderTargets.length;
  18437. while (--i >= 0) {
  18438. this.customRenderTargets[i].dispose();
  18439. }
  18440. this.customRenderTargets = [];
  18441. // Active Meshes
  18442. this._activeMeshes.dispose();
  18443. _super.prototype.dispose.call(this);
  18444. };
  18445. Object.defineProperty(Camera.prototype, "leftCamera", {
  18446. // ---- Camera rigs section ----
  18447. get: function () {
  18448. if (this._rigCameras.length < 1) {
  18449. return null;
  18450. }
  18451. return this._rigCameras[0];
  18452. },
  18453. enumerable: true,
  18454. configurable: true
  18455. });
  18456. Object.defineProperty(Camera.prototype, "rightCamera", {
  18457. get: function () {
  18458. if (this._rigCameras.length < 2) {
  18459. return null;
  18460. }
  18461. return this._rigCameras[1];
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. Camera.prototype.getLeftTarget = function () {
  18467. if (this._rigCameras.length < 1) {
  18468. return null;
  18469. }
  18470. return this._rigCameras[0].getTarget();
  18471. };
  18472. Camera.prototype.getRightTarget = function () {
  18473. if (this._rigCameras.length < 2) {
  18474. return null;
  18475. }
  18476. return this._rigCameras[1].getTarget();
  18477. };
  18478. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18479. if (this.cameraRigMode === mode) {
  18480. return;
  18481. }
  18482. while (this._rigCameras.length > 0) {
  18483. var camera = this._rigCameras.pop();
  18484. if (camera) {
  18485. camera.dispose();
  18486. }
  18487. }
  18488. this.cameraRigMode = mode;
  18489. this._cameraRigParams = {};
  18490. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18491. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18492. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18493. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18494. // create the rig cameras, unless none
  18495. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18496. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18497. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18498. if (leftCamera && rightCamera) {
  18499. this._rigCameras.push(leftCamera);
  18500. this._rigCameras.push(rightCamera);
  18501. }
  18502. }
  18503. switch (this.cameraRigMode) {
  18504. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18505. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18506. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18507. break;
  18508. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18509. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18510. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18511. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18512. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18513. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18514. break;
  18515. case Camera.RIG_MODE_VR:
  18516. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18517. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18518. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18519. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18520. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18521. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18522. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18523. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18524. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18525. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18526. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18527. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18528. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18529. if (metrics.compensateDistortion) {
  18530. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18531. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18532. }
  18533. break;
  18534. case Camera.RIG_MODE_WEBVR:
  18535. if (rigParams.vrDisplay) {
  18536. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18537. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18538. //Left eye
  18539. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18540. this._rigCameras[0].setCameraRigParameter("left", true);
  18541. //leaving this for future reference
  18542. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18543. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18544. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18545. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18546. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18547. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18548. this._rigCameras[0].parent = this;
  18549. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18550. //Right eye
  18551. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18552. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18553. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18554. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18555. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18556. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18557. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18558. this._rigCameras[1].parent = this;
  18559. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18560. if (Camera.UseAlternateWebVRRendering) {
  18561. this._rigCameras[1]._skipRendering = true;
  18562. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18563. }
  18564. }
  18565. break;
  18566. }
  18567. this._cascadePostProcessesToRigCams();
  18568. this.update();
  18569. };
  18570. Camera.prototype._getVRProjectionMatrix = function () {
  18571. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18572. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18573. return this._projectionMatrix;
  18574. };
  18575. Camera.prototype._updateCameraRotationMatrix = function () {
  18576. //Here for WebVR
  18577. };
  18578. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18579. //Here for WebVR
  18580. };
  18581. /**
  18582. * This function MUST be overwritten by the different WebVR cameras available.
  18583. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18584. */
  18585. Camera.prototype._getWebVRProjectionMatrix = function () {
  18586. return BABYLON.Matrix.Identity();
  18587. };
  18588. /**
  18589. * This function MUST be overwritten by the different WebVR cameras available.
  18590. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18591. */
  18592. Camera.prototype._getWebVRViewMatrix = function () {
  18593. return BABYLON.Matrix.Identity();
  18594. };
  18595. Camera.prototype.setCameraRigParameter = function (name, value) {
  18596. if (!this._cameraRigParams) {
  18597. this._cameraRigParams = {};
  18598. }
  18599. this._cameraRigParams[name] = value;
  18600. //provisionnally:
  18601. if (name === "interaxialDistance") {
  18602. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18603. }
  18604. };
  18605. /**
  18606. * needs to be overridden by children so sub has required properties to be copied
  18607. */
  18608. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18609. return null;
  18610. };
  18611. /**
  18612. * May need to be overridden by children
  18613. */
  18614. Camera.prototype._updateRigCameras = function () {
  18615. for (var i = 0; i < this._rigCameras.length; i++) {
  18616. this._rigCameras[i].minZ = this.minZ;
  18617. this._rigCameras[i].maxZ = this.maxZ;
  18618. this._rigCameras[i].fov = this.fov;
  18619. }
  18620. // only update viewport when ANAGLYPH
  18621. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18622. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18623. }
  18624. };
  18625. Camera.prototype._setupInputs = function () {
  18626. };
  18627. Camera.prototype.serialize = function () {
  18628. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18629. // Type
  18630. serializationObject.type = this.getClassName();
  18631. // Parent
  18632. if (this.parent) {
  18633. serializationObject.parentId = this.parent.id;
  18634. }
  18635. if (this.inputs) {
  18636. this.inputs.serialize(serializationObject);
  18637. }
  18638. // Animations
  18639. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18640. serializationObject.ranges = this.serializeAnimationRanges();
  18641. return serializationObject;
  18642. };
  18643. Camera.prototype.clone = function (name) {
  18644. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18645. };
  18646. Camera.prototype.getDirection = function (localAxis) {
  18647. var result = BABYLON.Vector3.Zero();
  18648. this.getDirectionToRef(localAxis, result);
  18649. return result;
  18650. };
  18651. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18652. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18653. };
  18654. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18655. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18656. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18657. switch (type) {
  18658. case "ArcRotateCamera":
  18659. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18660. case "DeviceOrientationCamera":
  18661. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18662. case "FollowCamera":
  18663. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18664. case "ArcFollowCamera":
  18665. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18666. case "GamepadCamera":
  18667. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18668. case "TouchCamera":
  18669. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18670. case "VirtualJoysticksCamera":
  18671. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18672. case "WebVRFreeCamera":
  18673. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18674. case "WebVRGamepadCamera":
  18675. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18676. case "VRDeviceOrientationFreeCamera":
  18677. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18678. case "VRDeviceOrientationGamepadCamera":
  18679. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18680. case "AnaglyphArcRotateCamera":
  18681. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18682. case "AnaglyphFreeCamera":
  18683. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18684. case "AnaglyphGamepadCamera":
  18685. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18686. case "AnaglyphUniversalCamera":
  18687. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18688. case "StereoscopicArcRotateCamera":
  18689. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18690. case "StereoscopicFreeCamera":
  18691. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18692. case "StereoscopicGamepadCamera":
  18693. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18694. case "StereoscopicUniversalCamera":
  18695. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18696. case "FreeCamera":// Forcing Universal here
  18697. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18698. default:// Universal Camera is the default value
  18699. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18700. }
  18701. };
  18702. Camera.prototype.computeWorldMatrix = function () {
  18703. return this.getWorldMatrix();
  18704. };
  18705. Camera.Parse = function (parsedCamera, scene) {
  18706. var type = parsedCamera.type;
  18707. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18708. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18709. // Parent
  18710. if (parsedCamera.parentId) {
  18711. camera._waitingParentId = parsedCamera.parentId;
  18712. }
  18713. //If camera has an input manager, let it parse inputs settings
  18714. if (camera.inputs) {
  18715. camera.inputs.parse(parsedCamera);
  18716. camera._setupInputs();
  18717. }
  18718. if (camera.setPosition) {
  18719. camera.position.copyFromFloats(0, 0, 0);
  18720. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18721. }
  18722. // Target
  18723. if (parsedCamera.target) {
  18724. if (camera.setTarget) {
  18725. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18726. }
  18727. }
  18728. // Apply 3d rig, when found
  18729. if (parsedCamera.cameraRigMode) {
  18730. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18731. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18732. }
  18733. // Animations
  18734. if (parsedCamera.animations) {
  18735. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18736. var parsedAnimation = parsedCamera.animations[animationIndex];
  18737. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18738. }
  18739. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18740. }
  18741. if (parsedCamera.autoAnimate) {
  18742. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18743. }
  18744. return camera;
  18745. };
  18746. // Statics
  18747. Camera._PERSPECTIVE_CAMERA = 0;
  18748. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18749. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18750. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18751. Camera._RIG_MODE_NONE = 0;
  18752. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18753. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18754. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18755. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18756. Camera._RIG_MODE_VR = 20;
  18757. Camera._RIG_MODE_WEBVR = 21;
  18758. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18759. Camera.UseAlternateWebVRRendering = false;
  18760. __decorate([
  18761. BABYLON.serializeAsVector3()
  18762. ], Camera.prototype, "position", void 0);
  18763. __decorate([
  18764. BABYLON.serializeAsVector3()
  18765. ], Camera.prototype, "upVector", void 0);
  18766. __decorate([
  18767. BABYLON.serialize()
  18768. ], Camera.prototype, "orthoLeft", void 0);
  18769. __decorate([
  18770. BABYLON.serialize()
  18771. ], Camera.prototype, "orthoRight", void 0);
  18772. __decorate([
  18773. BABYLON.serialize()
  18774. ], Camera.prototype, "orthoBottom", void 0);
  18775. __decorate([
  18776. BABYLON.serialize()
  18777. ], Camera.prototype, "orthoTop", void 0);
  18778. __decorate([
  18779. BABYLON.serialize()
  18780. ], Camera.prototype, "fov", void 0);
  18781. __decorate([
  18782. BABYLON.serialize()
  18783. ], Camera.prototype, "minZ", void 0);
  18784. __decorate([
  18785. BABYLON.serialize()
  18786. ], Camera.prototype, "maxZ", void 0);
  18787. __decorate([
  18788. BABYLON.serialize()
  18789. ], Camera.prototype, "inertia", void 0);
  18790. __decorate([
  18791. BABYLON.serialize()
  18792. ], Camera.prototype, "mode", void 0);
  18793. __decorate([
  18794. BABYLON.serialize()
  18795. ], Camera.prototype, "layerMask", void 0);
  18796. __decorate([
  18797. BABYLON.serialize()
  18798. ], Camera.prototype, "fovMode", void 0);
  18799. __decorate([
  18800. BABYLON.serialize()
  18801. ], Camera.prototype, "cameraRigMode", void 0);
  18802. __decorate([
  18803. BABYLON.serialize()
  18804. ], Camera.prototype, "interaxialDistance", void 0);
  18805. __decorate([
  18806. BABYLON.serialize()
  18807. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18808. return Camera;
  18809. }(BABYLON.Node));
  18810. BABYLON.Camera = Camera;
  18811. })(BABYLON || (BABYLON = {}));
  18812. //# sourceMappingURL=babylon.camera.js.map
  18813. var BABYLON;
  18814. (function (BABYLON) {
  18815. var RenderingManager = /** @class */ (function () {
  18816. function RenderingManager(scene) {
  18817. this._renderingGroups = new Array();
  18818. this._autoClearDepthStencil = {};
  18819. this._customOpaqueSortCompareFn = {};
  18820. this._customAlphaTestSortCompareFn = {};
  18821. this._customTransparentSortCompareFn = {};
  18822. this._renderinGroupInfo = null;
  18823. this._scene = scene;
  18824. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18825. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18826. }
  18827. }
  18828. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18829. if (depth === void 0) { depth = true; }
  18830. if (stencil === void 0) { stencil = true; }
  18831. if (this._depthStencilBufferAlreadyCleaned) {
  18832. return;
  18833. }
  18834. this._scene.getEngine().clear(null, false, depth, stencil);
  18835. this._depthStencilBufferAlreadyCleaned = true;
  18836. };
  18837. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18838. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18839. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18840. var info = null;
  18841. if (observable) {
  18842. if (!this._renderinGroupInfo) {
  18843. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18844. }
  18845. info = this._renderinGroupInfo;
  18846. info.scene = this._scene;
  18847. info.camera = this._scene.activeCamera;
  18848. }
  18849. // Dispatch sprites
  18850. if (renderSprites) {
  18851. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18852. var manager = this._scene.spriteManagers[index];
  18853. this.dispatchSprites(manager);
  18854. }
  18855. }
  18856. // Render
  18857. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18858. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18859. var renderingGroup = this._renderingGroups[index];
  18860. if (!renderingGroup && !observable)
  18861. continue;
  18862. var renderingGroupMask = 0;
  18863. // Fire PRECLEAR stage
  18864. if (observable && info) {
  18865. renderingGroupMask = Math.pow(2, index);
  18866. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18867. info.renderingGroupId = index;
  18868. observable.notifyObservers(info, renderingGroupMask);
  18869. }
  18870. // Clear depth/stencil if needed
  18871. if (RenderingManager.AUTOCLEAR) {
  18872. var autoClear = this._autoClearDepthStencil[index];
  18873. if (autoClear && autoClear.autoClear) {
  18874. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18875. }
  18876. }
  18877. if (observable && info) {
  18878. // Fire PREOPAQUE stage
  18879. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18880. observable.notifyObservers(info, renderingGroupMask);
  18881. // Fire PRETRANSPARENT stage
  18882. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18883. observable.notifyObservers(info, renderingGroupMask);
  18884. }
  18885. if (renderingGroup)
  18886. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18887. // Fire POSTTRANSPARENT stage
  18888. if (observable && info) {
  18889. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18890. observable.notifyObservers(info, renderingGroupMask);
  18891. }
  18892. }
  18893. };
  18894. RenderingManager.prototype.reset = function () {
  18895. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18896. var renderingGroup = this._renderingGroups[index];
  18897. if (renderingGroup) {
  18898. renderingGroup.prepare();
  18899. }
  18900. }
  18901. };
  18902. RenderingManager.prototype.dispose = function () {
  18903. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18904. var renderingGroup = this._renderingGroups[index];
  18905. if (renderingGroup) {
  18906. renderingGroup.dispose();
  18907. }
  18908. }
  18909. this._renderingGroups.length = 0;
  18910. };
  18911. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18912. if (this._renderingGroups[renderingGroupId] === undefined) {
  18913. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18914. }
  18915. };
  18916. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18917. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18918. this._prepareRenderingGroup(renderingGroupId);
  18919. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18920. };
  18921. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18922. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18923. this._prepareRenderingGroup(renderingGroupId);
  18924. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18925. };
  18926. /**
  18927. * @param subMesh The submesh to dispatch
  18928. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18929. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18930. */
  18931. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18932. if (mesh === undefined) {
  18933. mesh = subMesh.getMesh();
  18934. }
  18935. var renderingGroupId = mesh.renderingGroupId || 0;
  18936. this._prepareRenderingGroup(renderingGroupId);
  18937. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18938. };
  18939. /**
  18940. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18941. * This allowed control for front to back rendering or reversly depending of the special needs.
  18942. *
  18943. * @param renderingGroupId The rendering group id corresponding to its index
  18944. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18945. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18946. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18947. */
  18948. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18949. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18950. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18951. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18952. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18953. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18954. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18955. if (this._renderingGroups[renderingGroupId]) {
  18956. var group = this._renderingGroups[renderingGroupId];
  18957. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18958. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18959. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18960. }
  18961. };
  18962. /**
  18963. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18964. *
  18965. * @param renderingGroupId The rendering group id corresponding to its index
  18966. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18967. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18968. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18969. */
  18970. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18971. if (depth === void 0) { depth = true; }
  18972. if (stencil === void 0) { stencil = true; }
  18973. this._autoClearDepthStencil[renderingGroupId] = {
  18974. autoClear: autoClearDepthStencil,
  18975. depth: depth,
  18976. stencil: stencil
  18977. };
  18978. };
  18979. /**
  18980. * The max id used for rendering groups (not included)
  18981. */
  18982. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18983. /**
  18984. * The min id used for rendering groups (included)
  18985. */
  18986. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18987. /**
  18988. * Used to globally prevent autoclearing scenes.
  18989. */
  18990. RenderingManager.AUTOCLEAR = true;
  18991. return RenderingManager;
  18992. }());
  18993. BABYLON.RenderingManager = RenderingManager;
  18994. })(BABYLON || (BABYLON = {}));
  18995. //# sourceMappingURL=babylon.renderingManager.js.map
  18996. var BABYLON;
  18997. (function (BABYLON) {
  18998. var RenderingGroup = /** @class */ (function () {
  18999. /**
  19000. * Creates a new rendering group.
  19001. * @param index The rendering group index
  19002. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19003. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19004. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19005. */
  19006. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19007. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19008. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19009. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19010. this.index = index;
  19011. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19012. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19013. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19014. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19015. this._particleSystems = new BABYLON.SmartArray(256);
  19016. this._spriteManagers = new BABYLON.SmartArray(256);
  19017. this._edgesRenderers = new BABYLON.SmartArray(16);
  19018. this._scene = scene;
  19019. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19020. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19021. this.transparentSortCompareFn = transparentSortCompareFn;
  19022. }
  19023. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19024. /**
  19025. * Set the opaque sort comparison function.
  19026. * If null the sub meshes will be render in the order they were created
  19027. */
  19028. set: function (value) {
  19029. this._opaqueSortCompareFn = value;
  19030. if (value) {
  19031. this._renderOpaque = this.renderOpaqueSorted;
  19032. }
  19033. else {
  19034. this._renderOpaque = RenderingGroup.renderUnsorted;
  19035. }
  19036. },
  19037. enumerable: true,
  19038. configurable: true
  19039. });
  19040. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19041. /**
  19042. * Set the alpha test sort comparison function.
  19043. * If null the sub meshes will be render in the order they were created
  19044. */
  19045. set: function (value) {
  19046. this._alphaTestSortCompareFn = value;
  19047. if (value) {
  19048. this._renderAlphaTest = this.renderAlphaTestSorted;
  19049. }
  19050. else {
  19051. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19052. }
  19053. },
  19054. enumerable: true,
  19055. configurable: true
  19056. });
  19057. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19058. /**
  19059. * Set the transparent sort comparison function.
  19060. * If null the sub meshes will be render in the order they were created
  19061. */
  19062. set: function (value) {
  19063. if (value) {
  19064. this._transparentSortCompareFn = value;
  19065. }
  19066. else {
  19067. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19068. }
  19069. this._renderTransparent = this.renderTransparentSorted;
  19070. },
  19071. enumerable: true,
  19072. configurable: true
  19073. });
  19074. /**
  19075. * Render all the sub meshes contained in the group.
  19076. * @param customRenderFunction Used to override the default render behaviour of the group.
  19077. * @returns true if rendered some submeshes.
  19078. */
  19079. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19080. if (customRenderFunction) {
  19081. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19082. return;
  19083. }
  19084. var engine = this._scene.getEngine();
  19085. // Depth only
  19086. if (this._depthOnlySubMeshes.length !== 0) {
  19087. engine.setColorWrite(false);
  19088. this._renderAlphaTest(this._depthOnlySubMeshes);
  19089. engine.setColorWrite(true);
  19090. }
  19091. // Opaque
  19092. if (this._opaqueSubMeshes.length !== 0) {
  19093. this._renderOpaque(this._opaqueSubMeshes);
  19094. }
  19095. // Alpha test
  19096. if (this._alphaTestSubMeshes.length !== 0) {
  19097. this._renderAlphaTest(this._alphaTestSubMeshes);
  19098. }
  19099. var stencilState = engine.getStencilBuffer();
  19100. engine.setStencilBuffer(false);
  19101. // Sprites
  19102. if (renderSprites) {
  19103. this._renderSprites();
  19104. }
  19105. // Particles
  19106. if (renderParticles) {
  19107. this._renderParticles(activeMeshes);
  19108. }
  19109. if (this.onBeforeTransparentRendering) {
  19110. this.onBeforeTransparentRendering();
  19111. }
  19112. // Transparent
  19113. if (this._transparentSubMeshes.length !== 0) {
  19114. this._renderTransparent(this._transparentSubMeshes);
  19115. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19116. }
  19117. // Set back stencil to false in case it changes before the edge renderer.
  19118. engine.setStencilBuffer(false);
  19119. // Edges
  19120. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19121. this._edgesRenderers.data[edgesRendererIndex].render();
  19122. }
  19123. // Restore Stencil state.
  19124. engine.setStencilBuffer(stencilState);
  19125. };
  19126. /**
  19127. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19128. * @param subMeshes The submeshes to render
  19129. */
  19130. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19131. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19132. };
  19133. /**
  19134. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19135. * @param subMeshes The submeshes to render
  19136. */
  19137. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19138. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19139. };
  19140. /**
  19141. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19142. * @param subMeshes The submeshes to render
  19143. */
  19144. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19145. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19146. };
  19147. /**
  19148. * Renders the submeshes in a specified order.
  19149. * @param subMeshes The submeshes to sort before render
  19150. * @param sortCompareFn The comparison function use to sort
  19151. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19152. * @param transparent Specifies to activate blending if true
  19153. */
  19154. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19155. var subIndex = 0;
  19156. var subMesh;
  19157. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19158. for (; subIndex < subMeshes.length; subIndex++) {
  19159. subMesh = subMeshes.data[subIndex];
  19160. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19161. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19162. }
  19163. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19164. if (sortCompareFn) {
  19165. sortedArray.sort(sortCompareFn);
  19166. }
  19167. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19168. subMesh = sortedArray[subIndex];
  19169. if (transparent) {
  19170. var material = subMesh.getMaterial();
  19171. if (material && material.needDepthPrePass) {
  19172. var engine = material.getScene().getEngine();
  19173. engine.setColorWrite(false);
  19174. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19175. subMesh.render(false);
  19176. engine.setColorWrite(true);
  19177. }
  19178. }
  19179. subMesh.render(transparent);
  19180. }
  19181. };
  19182. /**
  19183. * Renders the submeshes in the order they were dispatched (no sort applied).
  19184. * @param subMeshes The submeshes to render
  19185. */
  19186. RenderingGroup.renderUnsorted = function (subMeshes) {
  19187. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19188. var submesh = subMeshes.data[subIndex];
  19189. submesh.render(false);
  19190. }
  19191. };
  19192. /**
  19193. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19194. * are rendered back to front if in the same alpha index.
  19195. *
  19196. * @param a The first submesh
  19197. * @param b The second submesh
  19198. * @returns The result of the comparison
  19199. */
  19200. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19201. // Alpha index first
  19202. if (a._alphaIndex > b._alphaIndex) {
  19203. return 1;
  19204. }
  19205. if (a._alphaIndex < b._alphaIndex) {
  19206. return -1;
  19207. }
  19208. // Then distance to camera
  19209. return RenderingGroup.backToFrontSortCompare(a, b);
  19210. };
  19211. /**
  19212. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19213. * are rendered back to front.
  19214. *
  19215. * @param a The first submesh
  19216. * @param b The second submesh
  19217. * @returns The result of the comparison
  19218. */
  19219. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19220. // Then distance to camera
  19221. if (a._distanceToCamera < b._distanceToCamera) {
  19222. return 1;
  19223. }
  19224. if (a._distanceToCamera > b._distanceToCamera) {
  19225. return -1;
  19226. }
  19227. return 0;
  19228. };
  19229. /**
  19230. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19231. * are rendered front to back (prevent overdraw).
  19232. *
  19233. * @param a The first submesh
  19234. * @param b The second submesh
  19235. * @returns The result of the comparison
  19236. */
  19237. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19238. // Then distance to camera
  19239. if (a._distanceToCamera < b._distanceToCamera) {
  19240. return -1;
  19241. }
  19242. if (a._distanceToCamera > b._distanceToCamera) {
  19243. return 1;
  19244. }
  19245. return 0;
  19246. };
  19247. /**
  19248. * Resets the different lists of submeshes to prepare a new frame.
  19249. */
  19250. RenderingGroup.prototype.prepare = function () {
  19251. this._opaqueSubMeshes.reset();
  19252. this._transparentSubMeshes.reset();
  19253. this._alphaTestSubMeshes.reset();
  19254. this._depthOnlySubMeshes.reset();
  19255. this._particleSystems.reset();
  19256. this._spriteManagers.reset();
  19257. this._edgesRenderers.reset();
  19258. };
  19259. RenderingGroup.prototype.dispose = function () {
  19260. this._opaqueSubMeshes.dispose();
  19261. this._transparentSubMeshes.dispose();
  19262. this._alphaTestSubMeshes.dispose();
  19263. this._depthOnlySubMeshes.dispose();
  19264. this._particleSystems.dispose();
  19265. this._spriteManagers.dispose();
  19266. this._edgesRenderers.dispose();
  19267. };
  19268. /**
  19269. * Inserts the submesh in its correct queue depending on its material.
  19270. * @param subMesh The submesh to dispatch
  19271. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19272. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19273. */
  19274. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19275. // Get mesh and materials if not provided
  19276. if (mesh === undefined) {
  19277. mesh = subMesh.getMesh();
  19278. }
  19279. if (material === undefined) {
  19280. material = subMesh.getMaterial();
  19281. }
  19282. if (material === null || material === undefined) {
  19283. return;
  19284. }
  19285. if (material.needAlphaBlendingForMesh(mesh)) {
  19286. this._transparentSubMeshes.push(subMesh);
  19287. }
  19288. else if (material.needAlphaTesting()) {
  19289. if (material.needDepthPrePass) {
  19290. this._depthOnlySubMeshes.push(subMesh);
  19291. }
  19292. this._alphaTestSubMeshes.push(subMesh);
  19293. }
  19294. else {
  19295. if (material.needDepthPrePass) {
  19296. this._depthOnlySubMeshes.push(subMesh);
  19297. }
  19298. this._opaqueSubMeshes.push(subMesh); // Opaque
  19299. }
  19300. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19301. this._edgesRenderers.push(mesh._edgesRenderer);
  19302. }
  19303. };
  19304. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19305. this._spriteManagers.push(spriteManager);
  19306. };
  19307. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19308. this._particleSystems.push(particleSystem);
  19309. };
  19310. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19311. if (this._particleSystems.length === 0) {
  19312. return;
  19313. }
  19314. // Particles
  19315. var activeCamera = this._scene.activeCamera;
  19316. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19317. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19318. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19319. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19320. continue;
  19321. }
  19322. var emitter = particleSystem.emitter;
  19323. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19324. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19325. }
  19326. }
  19327. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19328. };
  19329. RenderingGroup.prototype._renderSprites = function () {
  19330. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19331. return;
  19332. }
  19333. // Sprites
  19334. var activeCamera = this._scene.activeCamera;
  19335. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19336. for (var id = 0; id < this._spriteManagers.length; id++) {
  19337. var spriteManager = this._spriteManagers.data[id];
  19338. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19339. spriteManager.render();
  19340. }
  19341. }
  19342. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19343. };
  19344. return RenderingGroup;
  19345. }());
  19346. BABYLON.RenderingGroup = RenderingGroup;
  19347. })(BABYLON || (BABYLON = {}));
  19348. //# sourceMappingURL=babylon.renderingGroup.js.map
  19349. var BABYLON;
  19350. (function (BABYLON) {
  19351. var ClickInfo = /** @class */ (function () {
  19352. function ClickInfo() {
  19353. this._singleClick = false;
  19354. this._doubleClick = false;
  19355. this._hasSwiped = false;
  19356. this._ignore = false;
  19357. }
  19358. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19359. get: function () {
  19360. return this._singleClick;
  19361. },
  19362. set: function (b) {
  19363. this._singleClick = b;
  19364. },
  19365. enumerable: true,
  19366. configurable: true
  19367. });
  19368. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19369. get: function () {
  19370. return this._doubleClick;
  19371. },
  19372. set: function (b) {
  19373. this._doubleClick = b;
  19374. },
  19375. enumerable: true,
  19376. configurable: true
  19377. });
  19378. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19379. get: function () {
  19380. return this._hasSwiped;
  19381. },
  19382. set: function (b) {
  19383. this._hasSwiped = b;
  19384. },
  19385. enumerable: true,
  19386. configurable: true
  19387. });
  19388. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19389. get: function () {
  19390. return this._ignore;
  19391. },
  19392. set: function (b) {
  19393. this._ignore = b;
  19394. },
  19395. enumerable: true,
  19396. configurable: true
  19397. });
  19398. return ClickInfo;
  19399. }());
  19400. /**
  19401. * This class is used by the onRenderingGroupObservable
  19402. */
  19403. var RenderingGroupInfo = /** @class */ (function () {
  19404. function RenderingGroupInfo() {
  19405. }
  19406. /**
  19407. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19408. * This stage will be fired no matter what
  19409. */
  19410. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19411. /**
  19412. * Called before opaque object are rendered.
  19413. * This stage will be fired only if there's 3D Opaque content to render
  19414. */
  19415. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19416. /**
  19417. * Called after the opaque objects are rendered and before the transparent ones
  19418. * This stage will be fired only if there's 3D transparent content to render
  19419. */
  19420. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19421. /**
  19422. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19423. * This stage will be fired no matter what
  19424. */
  19425. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19426. return RenderingGroupInfo;
  19427. }());
  19428. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19429. /**
  19430. * Represents a scene to be rendered by the engine.
  19431. * @see http://doc.babylonjs.com/page.php?p=21911
  19432. */
  19433. var Scene = /** @class */ (function () {
  19434. /**
  19435. * @constructor
  19436. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19437. */
  19438. function Scene(engine) {
  19439. // Members
  19440. this.autoClear = true;
  19441. this.autoClearDepthAndStencil = true;
  19442. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19443. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19444. this.forceWireframe = false;
  19445. this._forcePointsCloud = false;
  19446. this.forceShowBoundingBoxes = false;
  19447. this.animationsEnabled = true;
  19448. this.useConstantAnimationDeltaTime = false;
  19449. this.constantlyUpdateMeshUnderPointer = false;
  19450. this.hoverCursor = "pointer";
  19451. this.defaultCursor = "";
  19452. /**
  19453. * This is used to call preventDefault() on pointer down
  19454. * in order to block unwanted artifacts like system double clicks
  19455. */
  19456. this.preventDefaultOnPointerDown = true;
  19457. // Metadata
  19458. this.metadata = null;
  19459. /**
  19460. * An event triggered when the scene is disposed.
  19461. * @type {BABYLON.Observable}
  19462. */
  19463. this.onDisposeObservable = new BABYLON.Observable();
  19464. /**
  19465. * An event triggered before rendering the scene (right after animations and physics)
  19466. * @type {BABYLON.Observable}
  19467. */
  19468. this.onBeforeRenderObservable = new BABYLON.Observable();
  19469. /**
  19470. * An event triggered after rendering the scene
  19471. * @type {BABYLON.Observable}
  19472. */
  19473. this.onAfterRenderObservable = new BABYLON.Observable();
  19474. /**
  19475. * An event triggered before animating the scene
  19476. * @type {BABYLON.Observable}
  19477. */
  19478. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19479. /**
  19480. * An event triggered after animations processing
  19481. * @type {BABYLON.Observable}
  19482. */
  19483. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19484. /**
  19485. * An event triggered before draw calls are ready to be sent
  19486. * @type {BABYLON.Observable}
  19487. */
  19488. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19489. /**
  19490. * An event triggered after draw calls have been sent
  19491. * @type {BABYLON.Observable}
  19492. */
  19493. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19494. /**
  19495. * An event triggered when physic simulation is about to be run
  19496. * @type {BABYLON.Observable}
  19497. */
  19498. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19499. /**
  19500. * An event triggered when physic simulation has been done
  19501. * @type {BABYLON.Observable}
  19502. */
  19503. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19504. /**
  19505. * An event triggered when the scene is ready
  19506. * @type {BABYLON.Observable}
  19507. */
  19508. this.onReadyObservable = new BABYLON.Observable();
  19509. /**
  19510. * An event triggered before rendering a camera
  19511. * @type {BABYLON.Observable}
  19512. */
  19513. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19514. /**
  19515. * An event triggered after rendering a camera
  19516. * @type {BABYLON.Observable}
  19517. */
  19518. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19519. /**
  19520. * An event triggered when active meshes evaluation is about to start
  19521. * @type {BABYLON.Observable}
  19522. */
  19523. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19524. /**
  19525. * An event triggered when active meshes evaluation is done
  19526. * @type {BABYLON.Observable}
  19527. */
  19528. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19529. /**
  19530. * An event triggered when particles rendering is about to start
  19531. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19532. * @type {BABYLON.Observable}
  19533. */
  19534. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19535. /**
  19536. * An event triggered when particles rendering is done
  19537. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19538. * @type {BABYLON.Observable}
  19539. */
  19540. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19541. /**
  19542. * An event triggered when sprites rendering is about to start
  19543. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19544. * @type {BABYLON.Observable}
  19545. */
  19546. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19547. /**
  19548. * An event triggered when sprites rendering is done
  19549. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19550. * @type {BABYLON.Observable}
  19551. */
  19552. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19553. /**
  19554. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19555. * @type {BABYLON.Observable}
  19556. */
  19557. this.onDataLoadedObservable = new BABYLON.Observable();
  19558. /**
  19559. * An event triggered when a camera is created
  19560. * @type {BABYLON.Observable}
  19561. */
  19562. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19563. /**
  19564. * An event triggered when a camera is removed
  19565. * @type {BABYLON.Observable}
  19566. */
  19567. this.onCameraRemovedObservable = new BABYLON.Observable();
  19568. /**
  19569. * An event triggered when a light is created
  19570. * @type {BABYLON.Observable}
  19571. */
  19572. this.onNewLightAddedObservable = new BABYLON.Observable();
  19573. /**
  19574. * An event triggered when a light is removed
  19575. * @type {BABYLON.Observable}
  19576. */
  19577. this.onLightRemovedObservable = new BABYLON.Observable();
  19578. /**
  19579. * An event triggered when a geometry is created
  19580. * @type {BABYLON.Observable}
  19581. */
  19582. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19583. /**
  19584. * An event triggered when a geometry is removed
  19585. * @type {BABYLON.Observable}
  19586. */
  19587. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19588. /**
  19589. * An event triggered when a transform node is created
  19590. * @type {BABYLON.Observable}
  19591. */
  19592. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19593. /**
  19594. * An event triggered when a transform node is removed
  19595. * @type {BABYLON.Observable}
  19596. */
  19597. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19598. /**
  19599. * An event triggered when a mesh is created
  19600. * @type {BABYLON.Observable}
  19601. */
  19602. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19603. /**
  19604. * An event triggered when a mesh is removed
  19605. * @type {BABYLON.Observable}
  19606. */
  19607. this.onMeshRemovedObservable = new BABYLON.Observable();
  19608. /**
  19609. * An event triggered when render targets are about to be rendered
  19610. * Can happen multiple times per frame.
  19611. * @type {BABYLON.Observable}
  19612. */
  19613. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19614. /**
  19615. * An event triggered when render targets were rendered.
  19616. * Can happen multiple times per frame.
  19617. * @type {BABYLON.Observable}
  19618. */
  19619. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19620. /**
  19621. * An event triggered before calculating deterministic simulation step
  19622. * @type {BABYLON.Observable}
  19623. */
  19624. this.onBeforeStepObservable = new BABYLON.Observable();
  19625. /**
  19626. * An event triggered after calculating deterministic simulation step
  19627. * @type {BABYLON.Observable}
  19628. */
  19629. this.onAfterStepObservable = new BABYLON.Observable();
  19630. /**
  19631. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19632. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19633. * 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)
  19634. */
  19635. this.onRenderingGroupObservable = new BABYLON.Observable();
  19636. // Animations
  19637. this.animations = [];
  19638. /**
  19639. * 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).
  19640. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19641. */
  19642. this.onPrePointerObservable = new BABYLON.Observable();
  19643. /**
  19644. * Observable event triggered each time an input event is received from the rendering canvas
  19645. */
  19646. this.onPointerObservable = new BABYLON.Observable();
  19647. this._meshPickProceed = false;
  19648. this._currentPickResult = null;
  19649. this._previousPickResult = null;
  19650. this._totalPointersPressed = 0;
  19651. this._doubleClickOccured = false;
  19652. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19653. this.cameraToUseForPointers = null;
  19654. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19655. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19656. this._startingPointerTime = 0;
  19657. this._previousStartingPointerTime = 0;
  19658. // Deterministic lockstep
  19659. this._timeAccumulator = 0;
  19660. this._currentStepId = 0;
  19661. this._currentInternalStep = 0;
  19662. // Keyboard
  19663. /**
  19664. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19665. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19666. */
  19667. this.onPreKeyboardObservable = new BABYLON.Observable();
  19668. /**
  19669. * Observable event triggered each time an keyboard event is received from the hosting window
  19670. */
  19671. this.onKeyboardObservable = new BABYLON.Observable();
  19672. // Coordinate system
  19673. /**
  19674. * use right-handed coordinate system on this scene.
  19675. * @type {boolean}
  19676. */
  19677. this._useRightHandedSystem = false;
  19678. // Fog
  19679. this._fogEnabled = true;
  19680. this._fogMode = Scene.FOGMODE_NONE;
  19681. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19682. this.fogDensity = 0.1;
  19683. this.fogStart = 0;
  19684. this.fogEnd = 1000.0;
  19685. // Lights
  19686. /**
  19687. * is shadow enabled on this scene.
  19688. * @type {boolean}
  19689. */
  19690. this._shadowsEnabled = true;
  19691. /**
  19692. * is light enabled on this scene.
  19693. * @type {boolean}
  19694. */
  19695. this._lightsEnabled = true;
  19696. /**
  19697. * All of the lights added to this scene.
  19698. * @see BABYLON.Light
  19699. * @type {BABYLON.Light[]}
  19700. */
  19701. this.lights = new Array();
  19702. // Cameras
  19703. /** All of the cameras added to this scene. */
  19704. this.cameras = new Array();
  19705. /** All of the active cameras added to this scene. */
  19706. this.activeCameras = new Array();
  19707. // Meshes
  19708. /**
  19709. * All of the tranform nodes added to this scene.
  19710. * @see BABYLON.TransformNode
  19711. * @type {BABYLON.TransformNode[]}
  19712. */
  19713. this.transformNodes = new Array();
  19714. /**
  19715. * All of the (abstract) meshes added to this scene.
  19716. * @see BABYLON.AbstractMesh
  19717. * @type {BABYLON.AbstractMesh[]}
  19718. */
  19719. this.meshes = new Array();
  19720. /**
  19721. * All of the animation groups added to this scene.
  19722. * @see BABYLON.AnimationGroup
  19723. * @type {BABYLON.AnimationGroup[]}
  19724. */
  19725. this.animationGroups = new Array();
  19726. // Geometries
  19727. this._geometries = new Array();
  19728. this.materials = new Array();
  19729. this.multiMaterials = new Array();
  19730. // Textures
  19731. this._texturesEnabled = true;
  19732. this.textures = new Array();
  19733. // Particles
  19734. this.particlesEnabled = true;
  19735. this.particleSystems = new Array();
  19736. // Sprites
  19737. this.spritesEnabled = true;
  19738. this.spriteManagers = new Array();
  19739. // Layers
  19740. this.layers = new Array();
  19741. this.highlightLayers = new Array();
  19742. // Skeletons
  19743. this._skeletonsEnabled = true;
  19744. this.skeletons = new Array();
  19745. // Morph targets
  19746. this.morphTargetManagers = new Array();
  19747. // Lens flares
  19748. this.lensFlaresEnabled = true;
  19749. this.lensFlareSystems = new Array();
  19750. // Collisions
  19751. this.collisionsEnabled = true;
  19752. /** Defines the gravity applied to this scene */
  19753. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19754. // Postprocesses
  19755. this.postProcesses = new Array();
  19756. this.postProcessesEnabled = true;
  19757. // Customs render targets
  19758. this.renderTargetsEnabled = true;
  19759. this.dumpNextRenderTargets = false;
  19760. this.customRenderTargets = new Array();
  19761. // Imported meshes
  19762. this.importedMeshesFiles = new Array();
  19763. // Probes
  19764. this.probesEnabled = true;
  19765. this.reflectionProbes = new Array();
  19766. this._actionManagers = new Array();
  19767. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19768. // Procedural textures
  19769. this.proceduralTexturesEnabled = true;
  19770. this._proceduralTextures = new Array();
  19771. this.soundTracks = new Array();
  19772. this._audioEnabled = true;
  19773. this._headphone = false;
  19774. // Performance counters
  19775. this._totalVertices = new BABYLON.PerfCounter();
  19776. this._activeIndices = new BABYLON.PerfCounter();
  19777. this._activeParticles = new BABYLON.PerfCounter();
  19778. this._activeBones = new BABYLON.PerfCounter();
  19779. this._animationTime = 0;
  19780. this.animationTimeScale = 1;
  19781. this._renderId = 0;
  19782. this._executeWhenReadyTimeoutId = -1;
  19783. this._intermediateRendering = false;
  19784. this._viewUpdateFlag = -1;
  19785. this._projectionUpdateFlag = -1;
  19786. this._alternateViewUpdateFlag = -1;
  19787. this._alternateProjectionUpdateFlag = -1;
  19788. this._toBeDisposed = new BABYLON.SmartArray(256);
  19789. this._activeRequests = new Array();
  19790. this._pendingData = new Array();
  19791. this._isDisposed = false;
  19792. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19793. this._activeMeshes = new BABYLON.SmartArray(256);
  19794. this._processedMaterials = new BABYLON.SmartArray(256);
  19795. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19796. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19797. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19798. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19799. this._activeAnimatables = new Array();
  19800. this._transformMatrix = BABYLON.Matrix.Zero();
  19801. this._useAlternateCameraConfiguration = false;
  19802. this._alternateRendering = false;
  19803. this.requireLightSorting = false;
  19804. this._activeMeshesFrozen = false;
  19805. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19806. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19807. this._engine.scenes.push(this);
  19808. this._uid = null;
  19809. this._renderingManager = new BABYLON.RenderingManager(this);
  19810. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19811. if (BABYLON.OutlineRenderer) {
  19812. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19813. }
  19814. if (BABYLON.Tools.IsWindowObjectExist()) {
  19815. this.attachControl();
  19816. }
  19817. //simplification queue
  19818. if (BABYLON.SimplificationQueue) {
  19819. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19820. }
  19821. //collision coordinator initialization. For now legacy per default.
  19822. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19823. // Uniform Buffer
  19824. this._createUbo();
  19825. // Default Image processing definition.
  19826. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19827. }
  19828. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19829. /** The fog is deactivated */
  19830. get: function () {
  19831. return Scene._FOGMODE_NONE;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19837. /** The fog density is following an exponential function */
  19838. get: function () {
  19839. return Scene._FOGMODE_EXP;
  19840. },
  19841. enumerable: true,
  19842. configurable: true
  19843. });
  19844. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19845. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19846. get: function () {
  19847. return Scene._FOGMODE_EXP2;
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19853. /** The fog density is following a linear function. */
  19854. get: function () {
  19855. return Scene._FOGMODE_LINEAR;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19861. /**
  19862. * Texture used in all pbr material as the reflection texture.
  19863. * As in the majority of the scene they are the same (exception for multi room and so on),
  19864. * this is easier to reference from here than from all the materials.
  19865. */
  19866. get: function () {
  19867. return this._environmentTexture;
  19868. },
  19869. /**
  19870. * Texture used in all pbr material as the reflection texture.
  19871. * As in the majority of the scene they are the same (exception for multi room and so on),
  19872. * this is easier to set here than in all the materials.
  19873. */
  19874. set: function (value) {
  19875. if (this._environmentTexture === value) {
  19876. return;
  19877. }
  19878. this._environmentTexture = value;
  19879. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19885. /**
  19886. * Default image processing configuration used either in the rendering
  19887. * Forward main pass or through the imageProcessingPostProcess if present.
  19888. * As in the majority of the scene they are the same (exception for multi camera),
  19889. * this is easier to reference from here than from all the materials and post process.
  19890. *
  19891. * No setter as we it is a shared configuration, you can set the values instead.
  19892. */
  19893. get: function () {
  19894. return this._imageProcessingConfiguration;
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19900. get: function () {
  19901. return this._forcePointsCloud;
  19902. },
  19903. set: function (value) {
  19904. if (this._forcePointsCloud === value) {
  19905. return;
  19906. }
  19907. this._forcePointsCloud = value;
  19908. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(Scene.prototype, "onDispose", {
  19914. /** A function to be executed when this scene is disposed. */
  19915. set: function (callback) {
  19916. if (this._onDisposeObserver) {
  19917. this.onDisposeObservable.remove(this._onDisposeObserver);
  19918. }
  19919. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19920. },
  19921. enumerable: true,
  19922. configurable: true
  19923. });
  19924. Object.defineProperty(Scene.prototype, "beforeRender", {
  19925. /** A function to be executed before rendering this scene */
  19926. set: function (callback) {
  19927. if (this._onBeforeRenderObserver) {
  19928. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19929. }
  19930. if (callback) {
  19931. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19932. }
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(Scene.prototype, "afterRender", {
  19938. /** A function to be executed after rendering this scene */
  19939. set: function (callback) {
  19940. if (this._onAfterRenderObserver) {
  19941. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19942. }
  19943. if (callback) {
  19944. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19945. }
  19946. },
  19947. enumerable: true,
  19948. configurable: true
  19949. });
  19950. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19951. set: function (callback) {
  19952. if (this._onBeforeCameraRenderObserver) {
  19953. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19954. }
  19955. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19956. },
  19957. enumerable: true,
  19958. configurable: true
  19959. });
  19960. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19961. set: function (callback) {
  19962. if (this._onAfterCameraRenderObserver) {
  19963. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19964. }
  19965. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19971. get: function () {
  19972. if (!this._gamepadManager) {
  19973. this._gamepadManager = new BABYLON.GamepadManager(this);
  19974. }
  19975. return this._gamepadManager;
  19976. },
  19977. enumerable: true,
  19978. configurable: true
  19979. });
  19980. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19981. get: function () {
  19982. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19983. },
  19984. enumerable: true,
  19985. configurable: true
  19986. });
  19987. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19988. get: function () {
  19989. return this._useRightHandedSystem;
  19990. },
  19991. set: function (value) {
  19992. if (this._useRightHandedSystem === value) {
  19993. return;
  19994. }
  19995. this._useRightHandedSystem = value;
  19996. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Scene.prototype.setStepId = function (newStepId) {
  20002. this._currentStepId = newStepId;
  20003. };
  20004. ;
  20005. Scene.prototype.getStepId = function () {
  20006. return this._currentStepId;
  20007. };
  20008. ;
  20009. Scene.prototype.getInternalStep = function () {
  20010. return this._currentInternalStep;
  20011. };
  20012. ;
  20013. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20014. get: function () {
  20015. return this._fogEnabled;
  20016. },
  20017. /**
  20018. * is fog enabled on this scene.
  20019. */
  20020. set: function (value) {
  20021. if (this._fogEnabled === value) {
  20022. return;
  20023. }
  20024. this._fogEnabled = value;
  20025. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. Object.defineProperty(Scene.prototype, "fogMode", {
  20031. get: function () {
  20032. return this._fogMode;
  20033. },
  20034. set: function (value) {
  20035. if (this._fogMode === value) {
  20036. return;
  20037. }
  20038. this._fogMode = value;
  20039. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20045. get: function () {
  20046. return this._shadowsEnabled;
  20047. },
  20048. set: function (value) {
  20049. if (this._shadowsEnabled === value) {
  20050. return;
  20051. }
  20052. this._shadowsEnabled = value;
  20053. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20054. },
  20055. enumerable: true,
  20056. configurable: true
  20057. });
  20058. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20059. get: function () {
  20060. return this._lightsEnabled;
  20061. },
  20062. set: function (value) {
  20063. if (this._lightsEnabled === value) {
  20064. return;
  20065. }
  20066. this._lightsEnabled = value;
  20067. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20073. /** The default material used on meshes when no material is affected */
  20074. get: function () {
  20075. if (!this._defaultMaterial) {
  20076. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20077. }
  20078. return this._defaultMaterial;
  20079. },
  20080. /** The default material used on meshes when no material is affected */
  20081. set: function (value) {
  20082. this._defaultMaterial = value;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20088. get: function () {
  20089. return this._texturesEnabled;
  20090. },
  20091. set: function (value) {
  20092. if (this._texturesEnabled === value) {
  20093. return;
  20094. }
  20095. this._texturesEnabled = value;
  20096. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20102. get: function () {
  20103. return this._skeletonsEnabled;
  20104. },
  20105. set: function (value) {
  20106. if (this._skeletonsEnabled === value) {
  20107. return;
  20108. }
  20109. this._skeletonsEnabled = value;
  20110. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20116. get: function () {
  20117. if (!this._postProcessRenderPipelineManager) {
  20118. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20119. }
  20120. return this._postProcessRenderPipelineManager;
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20126. get: function () {
  20127. if (!this._mainSoundTrack) {
  20128. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20129. }
  20130. return this._mainSoundTrack;
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20136. get: function () {
  20137. return this._alternateRendering;
  20138. },
  20139. enumerable: true,
  20140. configurable: true
  20141. });
  20142. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20143. get: function () {
  20144. return this._frustumPlanes;
  20145. },
  20146. enumerable: true,
  20147. configurable: true
  20148. });
  20149. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20150. /**
  20151. * Gets the current geometry buffer associated to the scene.
  20152. */
  20153. get: function () {
  20154. return this._geometryBufferRenderer;
  20155. },
  20156. /**
  20157. * Sets the current geometry buffer for the scene.
  20158. */
  20159. set: function (geometryBufferRenderer) {
  20160. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20161. this._geometryBufferRenderer = geometryBufferRenderer;
  20162. }
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. Object.defineProperty(Scene.prototype, "debugLayer", {
  20168. // Properties
  20169. get: function () {
  20170. if (!this._debugLayer) {
  20171. this._debugLayer = new BABYLON.DebugLayer(this);
  20172. }
  20173. return this._debugLayer;
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20179. get: function () {
  20180. return this._workerCollisions;
  20181. },
  20182. set: function (enabled) {
  20183. if (!BABYLON.CollisionCoordinatorLegacy) {
  20184. return;
  20185. }
  20186. enabled = (enabled && !!Worker);
  20187. this._workerCollisions = enabled;
  20188. if (this.collisionCoordinator) {
  20189. this.collisionCoordinator.destroy();
  20190. }
  20191. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20192. this.collisionCoordinator.init(this);
  20193. },
  20194. enumerable: true,
  20195. configurable: true
  20196. });
  20197. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20198. get: function () {
  20199. return this._selectionOctree;
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20205. /**
  20206. * The mesh that is currently under the pointer.
  20207. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20208. */
  20209. get: function () {
  20210. return this._pointerOverMesh;
  20211. },
  20212. enumerable: true,
  20213. configurable: true
  20214. });
  20215. Object.defineProperty(Scene.prototype, "pointerX", {
  20216. /**
  20217. * Current on-screen X position of the pointer
  20218. * @return {number} X position of the pointer
  20219. */
  20220. get: function () {
  20221. return this._pointerX;
  20222. },
  20223. enumerable: true,
  20224. configurable: true
  20225. });
  20226. Object.defineProperty(Scene.prototype, "pointerY", {
  20227. /**
  20228. * Current on-screen Y position of the pointer
  20229. * @return {number} Y position of the pointer
  20230. */
  20231. get: function () {
  20232. return this._pointerY;
  20233. },
  20234. enumerable: true,
  20235. configurable: true
  20236. });
  20237. Scene.prototype.getCachedMaterial = function () {
  20238. return this._cachedMaterial;
  20239. };
  20240. Scene.prototype.getCachedEffect = function () {
  20241. return this._cachedEffect;
  20242. };
  20243. Scene.prototype.getCachedVisibility = function () {
  20244. return this._cachedVisibility;
  20245. };
  20246. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20247. if (visibility === void 0) { visibility = 1; }
  20248. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20249. };
  20250. Scene.prototype.getBoundingBoxRenderer = function () {
  20251. if (!this._boundingBoxRenderer) {
  20252. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20253. }
  20254. return this._boundingBoxRenderer;
  20255. };
  20256. Scene.prototype.getOutlineRenderer = function () {
  20257. return this._outlineRenderer;
  20258. };
  20259. Scene.prototype.getEngine = function () {
  20260. return this._engine;
  20261. };
  20262. Scene.prototype.getTotalVertices = function () {
  20263. return this._totalVertices.current;
  20264. };
  20265. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20266. get: function () {
  20267. return this._totalVertices;
  20268. },
  20269. enumerable: true,
  20270. configurable: true
  20271. });
  20272. Scene.prototype.getActiveIndices = function () {
  20273. return this._activeIndices.current;
  20274. };
  20275. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20276. get: function () {
  20277. return this._activeIndices;
  20278. },
  20279. enumerable: true,
  20280. configurable: true
  20281. });
  20282. Scene.prototype.getActiveParticles = function () {
  20283. return this._activeParticles.current;
  20284. };
  20285. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20286. get: function () {
  20287. return this._activeParticles;
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Scene.prototype.getActiveBones = function () {
  20293. return this._activeBones.current;
  20294. };
  20295. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20296. get: function () {
  20297. return this._activeBones;
  20298. },
  20299. enumerable: true,
  20300. configurable: true
  20301. });
  20302. // Stats
  20303. Scene.prototype.getInterFramePerfCounter = function () {
  20304. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20305. return 0;
  20306. };
  20307. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20308. get: function () {
  20309. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20310. return null;
  20311. },
  20312. enumerable: true,
  20313. configurable: true
  20314. });
  20315. Scene.prototype.getLastFrameDuration = function () {
  20316. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20317. return 0;
  20318. };
  20319. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20320. get: function () {
  20321. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20322. return null;
  20323. },
  20324. enumerable: true,
  20325. configurable: true
  20326. });
  20327. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20328. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20329. return 0;
  20330. };
  20331. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20332. get: function () {
  20333. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20334. return null;
  20335. },
  20336. enumerable: true,
  20337. configurable: true
  20338. });
  20339. Scene.prototype.getActiveMeshes = function () {
  20340. return this._activeMeshes;
  20341. };
  20342. Scene.prototype.getRenderTargetsDuration = function () {
  20343. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20344. return 0;
  20345. };
  20346. Scene.prototype.getRenderDuration = function () {
  20347. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20348. return 0;
  20349. };
  20350. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20351. get: function () {
  20352. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20353. return null;
  20354. },
  20355. enumerable: true,
  20356. configurable: true
  20357. });
  20358. Scene.prototype.getParticlesDuration = function () {
  20359. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20360. return 0;
  20361. };
  20362. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20363. get: function () {
  20364. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20365. return null;
  20366. },
  20367. enumerable: true,
  20368. configurable: true
  20369. });
  20370. Scene.prototype.getSpritesDuration = function () {
  20371. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20372. return 0;
  20373. };
  20374. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20375. get: function () {
  20376. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20377. return null;
  20378. },
  20379. enumerable: true,
  20380. configurable: true
  20381. });
  20382. Scene.prototype.getAnimationRatio = function () {
  20383. return this._animationRatio;
  20384. };
  20385. Scene.prototype.getRenderId = function () {
  20386. return this._renderId;
  20387. };
  20388. Scene.prototype.incrementRenderId = function () {
  20389. this._renderId++;
  20390. };
  20391. Scene.prototype._updatePointerPosition = function (evt) {
  20392. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20393. if (!canvasRect) {
  20394. return;
  20395. }
  20396. this._pointerX = evt.clientX - canvasRect.left;
  20397. this._pointerY = evt.clientY - canvasRect.top;
  20398. this._unTranslatedPointerX = this._pointerX;
  20399. this._unTranslatedPointerY = this._pointerY;
  20400. };
  20401. Scene.prototype._createUbo = function () {
  20402. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20403. this._sceneUbo.addUniform("viewProjection", 16);
  20404. this._sceneUbo.addUniform("view", 16);
  20405. };
  20406. Scene.prototype._createAlternateUbo = function () {
  20407. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20408. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20409. this._alternateSceneUbo.addUniform("view", 16);
  20410. };
  20411. // Pointers handling
  20412. /**
  20413. * Use this method to simulate a pointer move on a mesh
  20414. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20415. */
  20416. Scene.prototype.simulatePointerMove = function (pickResult) {
  20417. var evt = new PointerEvent("pointermove");
  20418. return this._processPointerMove(pickResult, evt);
  20419. };
  20420. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20421. var canvas = this._engine.getRenderingCanvas();
  20422. if (!canvas) {
  20423. return this;
  20424. }
  20425. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20426. this.setPointerOverSprite(null);
  20427. this.setPointerOverMesh(pickResult.pickedMesh);
  20428. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20429. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20430. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20431. }
  20432. else {
  20433. canvas.style.cursor = this.hoverCursor;
  20434. }
  20435. }
  20436. else {
  20437. canvas.style.cursor = this.defaultCursor;
  20438. }
  20439. }
  20440. else {
  20441. this.setPointerOverMesh(null);
  20442. // Sprites
  20443. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20444. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20445. this.setPointerOverSprite(pickResult.pickedSprite);
  20446. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20447. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20448. }
  20449. else {
  20450. canvas.style.cursor = this.hoverCursor;
  20451. }
  20452. }
  20453. else {
  20454. this.setPointerOverSprite(null);
  20455. // Restore pointer
  20456. canvas.style.cursor = this.defaultCursor;
  20457. }
  20458. }
  20459. if (pickResult) {
  20460. if (this.onPointerMove) {
  20461. this.onPointerMove(evt, pickResult);
  20462. }
  20463. if (this.onPointerObservable.hasObservers()) {
  20464. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20465. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20466. this.onPointerObservable.notifyObservers(pi, type);
  20467. }
  20468. }
  20469. return this;
  20470. };
  20471. /**
  20472. * Use this method to simulate a pointer down on a mesh
  20473. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20474. */
  20475. Scene.prototype.simulatePointerDown = function (pickResult) {
  20476. var evt = new PointerEvent("pointerdown");
  20477. return this._processPointerDown(pickResult, evt);
  20478. };
  20479. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20480. var _this = this;
  20481. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20482. this._pickedDownMesh = pickResult.pickedMesh;
  20483. var actionManager = pickResult.pickedMesh.actionManager;
  20484. if (actionManager) {
  20485. if (actionManager.hasPickTriggers) {
  20486. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20487. switch (evt.button) {
  20488. case 0:
  20489. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20490. break;
  20491. case 1:
  20492. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20493. break;
  20494. case 2:
  20495. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20496. break;
  20497. }
  20498. }
  20499. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20500. window.setTimeout(function () {
  20501. 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);
  20502. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20503. if (_this._totalPointersPressed !== 0 &&
  20504. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20505. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20506. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20507. _this._startingPointerTime = 0;
  20508. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20509. }
  20510. }
  20511. }, Scene.LongPressDelay);
  20512. }
  20513. }
  20514. }
  20515. if (pickResult) {
  20516. if (this.onPointerDown) {
  20517. this.onPointerDown(evt, pickResult);
  20518. }
  20519. if (this.onPointerObservable.hasObservers()) {
  20520. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20521. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20522. this.onPointerObservable.notifyObservers(pi, type);
  20523. }
  20524. }
  20525. return this;
  20526. };
  20527. /**
  20528. * Use this method to simulate a pointer up on a mesh
  20529. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20530. */
  20531. Scene.prototype.simulatePointerUp = function (pickResult) {
  20532. var evt = new PointerEvent("pointerup");
  20533. var clickInfo = new ClickInfo();
  20534. clickInfo.singleClick = true;
  20535. clickInfo.ignore = true;
  20536. return this._processPointerUp(pickResult, evt, clickInfo);
  20537. };
  20538. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20539. if (pickResult && pickResult && pickResult.pickedMesh) {
  20540. this._pickedUpMesh = pickResult.pickedMesh;
  20541. if (this._pickedDownMesh === this._pickedUpMesh) {
  20542. if (this.onPointerPick) {
  20543. this.onPointerPick(evt, pickResult);
  20544. }
  20545. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20546. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20547. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20548. this.onPointerObservable.notifyObservers(pi, type);
  20549. }
  20550. }
  20551. if (pickResult.pickedMesh.actionManager) {
  20552. if (clickInfo.ignore) {
  20553. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20554. }
  20555. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20556. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20557. }
  20558. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20559. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20560. }
  20561. }
  20562. }
  20563. if (this._pickedDownMesh &&
  20564. this._pickedDownMesh.actionManager &&
  20565. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20566. this._pickedDownMesh !== this._pickedUpMesh) {
  20567. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20568. }
  20569. if (this.onPointerUp) {
  20570. this.onPointerUp(evt, pickResult);
  20571. }
  20572. if (this.onPointerObservable.hasObservers()) {
  20573. if (!clickInfo.ignore) {
  20574. if (!clickInfo.hasSwiped) {
  20575. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20576. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20577. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20578. this.onPointerObservable.notifyObservers(pi, type);
  20579. }
  20580. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20581. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20582. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20583. this.onPointerObservable.notifyObservers(pi, type);
  20584. }
  20585. }
  20586. }
  20587. else {
  20588. var type = BABYLON.PointerEventTypes.POINTERUP;
  20589. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20590. this.onPointerObservable.notifyObservers(pi, type);
  20591. }
  20592. }
  20593. return this;
  20594. };
  20595. /**
  20596. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20597. * @param attachUp defines if you want to attach events to pointerup
  20598. * @param attachDown defines if you want to attach events to pointerdown
  20599. * @param attachMove defines if you want to attach events to pointermove
  20600. */
  20601. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20602. var _this = this;
  20603. if (attachUp === void 0) { attachUp = true; }
  20604. if (attachDown === void 0) { attachDown = true; }
  20605. if (attachMove === void 0) { attachMove = true; }
  20606. this._initActionManager = function (act, clickInfo) {
  20607. if (!_this._meshPickProceed) {
  20608. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20609. _this._currentPickResult = pickResult;
  20610. if (pickResult) {
  20611. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20612. }
  20613. _this._meshPickProceed = true;
  20614. }
  20615. return act;
  20616. };
  20617. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20618. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20619. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20620. btn !== _this._previousButtonPressed) {
  20621. _this._doubleClickOccured = false;
  20622. clickInfo.singleClick = true;
  20623. clickInfo.ignore = false;
  20624. cb(clickInfo, _this._currentPickResult);
  20625. }
  20626. };
  20627. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20628. var clickInfo = new ClickInfo();
  20629. _this._currentPickResult = null;
  20630. var act = null;
  20631. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20632. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20633. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20634. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20635. act = _this._initActionManager(act, clickInfo);
  20636. if (act)
  20637. checkPicking = act.hasPickTriggers;
  20638. }
  20639. if (checkPicking) {
  20640. var btn = evt.button;
  20641. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20642. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20643. if (!clickInfo.hasSwiped) {
  20644. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20645. if (!checkSingleClickImmediately) {
  20646. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20647. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20648. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20649. act = _this._initActionManager(act, clickInfo);
  20650. if (act)
  20651. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20652. }
  20653. }
  20654. if (checkSingleClickImmediately) {
  20655. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20656. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20657. btn !== _this._previousButtonPressed) {
  20658. clickInfo.singleClick = true;
  20659. cb(clickInfo, _this._currentPickResult);
  20660. }
  20661. }
  20662. else {
  20663. // wait that no double click has been raised during the double click delay
  20664. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20665. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20666. }
  20667. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20668. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20669. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20670. act = _this._initActionManager(act, clickInfo);
  20671. if (act)
  20672. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20673. }
  20674. if (checkDoubleClick) {
  20675. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20676. if (btn === _this._previousButtonPressed &&
  20677. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20678. !_this._doubleClickOccured) {
  20679. // pointer has not moved for 2 clicks, it's a double click
  20680. if (!clickInfo.hasSwiped &&
  20681. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20682. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20683. _this._previousStartingPointerTime = 0;
  20684. _this._doubleClickOccured = true;
  20685. clickInfo.doubleClick = true;
  20686. clickInfo.ignore = false;
  20687. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20688. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20689. }
  20690. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20691. cb(clickInfo, _this._currentPickResult);
  20692. }
  20693. else {
  20694. _this._doubleClickOccured = false;
  20695. _this._previousStartingPointerTime = _this._startingPointerTime;
  20696. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20697. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20698. _this._previousButtonPressed = btn;
  20699. if (Scene.ExclusiveDoubleClickMode) {
  20700. if (_this._previousDelayedSimpleClickTimeout) {
  20701. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20702. }
  20703. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20704. cb(clickInfo, _this._previousPickResult);
  20705. }
  20706. else {
  20707. cb(clickInfo, _this._currentPickResult);
  20708. }
  20709. }
  20710. }
  20711. else {
  20712. _this._doubleClickOccured = false;
  20713. _this._previousStartingPointerTime = _this._startingPointerTime;
  20714. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20715. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20716. _this._previousButtonPressed = btn;
  20717. }
  20718. }
  20719. }
  20720. }
  20721. clickInfo.ignore = true;
  20722. cb(clickInfo, _this._currentPickResult);
  20723. };
  20724. this._spritePredicate = function (sprite) {
  20725. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20726. };
  20727. this._onPointerMove = function (evt) {
  20728. _this._updatePointerPosition(evt);
  20729. // PreObservable support
  20730. if (_this.onPrePointerObservable.hasObservers()) {
  20731. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20732. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20733. _this.onPrePointerObservable.notifyObservers(pi, type);
  20734. if (pi.skipOnPointerObservable) {
  20735. return;
  20736. }
  20737. }
  20738. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20739. return;
  20740. }
  20741. if (!_this.pointerMovePredicate) {
  20742. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20743. }
  20744. // Meshes
  20745. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20746. _this._processPointerMove(pickResult, evt);
  20747. };
  20748. this._onPointerDown = function (evt) {
  20749. _this._totalPointersPressed++;
  20750. _this._pickedDownMesh = null;
  20751. _this._meshPickProceed = false;
  20752. _this._updatePointerPosition(evt);
  20753. if (_this.preventDefaultOnPointerDown && canvas) {
  20754. evt.preventDefault();
  20755. canvas.focus();
  20756. }
  20757. // PreObservable support
  20758. if (_this.onPrePointerObservable.hasObservers()) {
  20759. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20760. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20761. _this.onPrePointerObservable.notifyObservers(pi, type);
  20762. if (pi.skipOnPointerObservable) {
  20763. return;
  20764. }
  20765. }
  20766. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20767. return;
  20768. }
  20769. _this._startingPointerPosition.x = _this._pointerX;
  20770. _this._startingPointerPosition.y = _this._pointerY;
  20771. _this._startingPointerTime = new Date().getTime();
  20772. if (!_this.pointerDownPredicate) {
  20773. _this.pointerDownPredicate = function (mesh) {
  20774. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20775. };
  20776. }
  20777. // Meshes
  20778. _this._pickedDownMesh = null;
  20779. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20780. _this._processPointerDown(pickResult, evt);
  20781. // Sprites
  20782. _this._pickedDownSprite = null;
  20783. if (_this.spriteManagers.length > 0) {
  20784. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20785. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20786. if (pickResult.pickedSprite.actionManager) {
  20787. _this._pickedDownSprite = pickResult.pickedSprite;
  20788. switch (evt.button) {
  20789. case 0:
  20790. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20791. break;
  20792. case 1:
  20793. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20794. break;
  20795. case 2:
  20796. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20797. break;
  20798. }
  20799. if (pickResult.pickedSprite.actionManager) {
  20800. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20801. }
  20802. }
  20803. }
  20804. }
  20805. };
  20806. this._onPointerUp = function (evt) {
  20807. if (_this._totalPointersPressed === 0) {
  20808. return; // So we need to test it the pointer down was pressed before.
  20809. }
  20810. _this._totalPointersPressed--;
  20811. _this._pickedUpMesh = null;
  20812. _this._meshPickProceed = false;
  20813. _this._updatePointerPosition(evt);
  20814. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20815. // PreObservable support
  20816. if (_this.onPrePointerObservable.hasObservers()) {
  20817. if (!clickInfo.ignore) {
  20818. if (!clickInfo.hasSwiped) {
  20819. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20820. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20821. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20822. _this.onPrePointerObservable.notifyObservers(pi, type);
  20823. if (pi.skipOnPointerObservable) {
  20824. return;
  20825. }
  20826. }
  20827. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20828. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20829. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20830. _this.onPrePointerObservable.notifyObservers(pi, type);
  20831. if (pi.skipOnPointerObservable) {
  20832. return;
  20833. }
  20834. }
  20835. }
  20836. }
  20837. else {
  20838. var type = BABYLON.PointerEventTypes.POINTERUP;
  20839. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20840. _this.onPrePointerObservable.notifyObservers(pi, type);
  20841. if (pi.skipOnPointerObservable) {
  20842. return;
  20843. }
  20844. }
  20845. }
  20846. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20847. return;
  20848. }
  20849. if (!_this.pointerUpPredicate) {
  20850. _this.pointerUpPredicate = function (mesh) {
  20851. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20852. };
  20853. }
  20854. // Meshes
  20855. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20856. _this._initActionManager(null, clickInfo);
  20857. }
  20858. if (!pickResult) {
  20859. pickResult = _this._currentPickResult;
  20860. }
  20861. _this._processPointerUp(pickResult, evt, clickInfo);
  20862. // Sprites
  20863. if (_this.spriteManagers.length > 0) {
  20864. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20865. if (spritePickResult) {
  20866. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20867. if (spritePickResult.pickedSprite.actionManager) {
  20868. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20869. if (spritePickResult.pickedSprite.actionManager) {
  20870. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20871. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20872. }
  20873. }
  20874. }
  20875. }
  20876. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20877. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20878. }
  20879. }
  20880. }
  20881. _this._previousPickResult = _this._currentPickResult;
  20882. });
  20883. };
  20884. this._onKeyDown = function (evt) {
  20885. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20886. if (_this.onPreKeyboardObservable.hasObservers()) {
  20887. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20888. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20889. if (pi.skipOnPointerObservable) {
  20890. return;
  20891. }
  20892. }
  20893. if (_this.onKeyboardObservable.hasObservers()) {
  20894. var pi = new BABYLON.KeyboardInfo(type, evt);
  20895. _this.onKeyboardObservable.notifyObservers(pi, type);
  20896. }
  20897. if (_this.actionManager) {
  20898. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20899. }
  20900. };
  20901. this._onKeyUp = function (evt) {
  20902. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20903. if (_this.onPreKeyboardObservable.hasObservers()) {
  20904. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20905. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20906. if (pi.skipOnPointerObservable) {
  20907. return;
  20908. }
  20909. }
  20910. if (_this.onKeyboardObservable.hasObservers()) {
  20911. var pi = new BABYLON.KeyboardInfo(type, evt);
  20912. _this.onKeyboardObservable.notifyObservers(pi, type);
  20913. }
  20914. if (_this.actionManager) {
  20915. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20916. }
  20917. };
  20918. var engine = this.getEngine();
  20919. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20920. if (!canvas) {
  20921. return;
  20922. }
  20923. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20924. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20925. });
  20926. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20927. if (!canvas) {
  20928. return;
  20929. }
  20930. canvas.removeEventListener("keydown", _this._onKeyDown);
  20931. canvas.removeEventListener("keyup", _this._onKeyUp);
  20932. });
  20933. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20934. var canvas = this._engine.getRenderingCanvas();
  20935. if (!canvas) {
  20936. return;
  20937. }
  20938. if (attachMove) {
  20939. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20940. // Wheel
  20941. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20942. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20943. }
  20944. if (attachDown) {
  20945. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20946. }
  20947. if (attachUp) {
  20948. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20949. }
  20950. canvas.tabIndex = 1;
  20951. };
  20952. Scene.prototype.detachControl = function () {
  20953. var engine = this.getEngine();
  20954. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20955. var canvas = engine.getRenderingCanvas();
  20956. if (!canvas) {
  20957. return;
  20958. }
  20959. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20960. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20961. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20962. if (this._onCanvasBlurObserver) {
  20963. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20964. }
  20965. if (this._onCanvasFocusObserver) {
  20966. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20967. }
  20968. // Wheel
  20969. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20970. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20971. // Keyboard
  20972. canvas.removeEventListener("keydown", this._onKeyDown);
  20973. canvas.removeEventListener("keyup", this._onKeyUp);
  20974. // Observables
  20975. this.onKeyboardObservable.clear();
  20976. this.onPreKeyboardObservable.clear();
  20977. this.onPointerObservable.clear();
  20978. this.onPrePointerObservable.clear();
  20979. };
  20980. /**
  20981. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20982. * Delay loaded resources are not taking in account
  20983. * @return true if all required resources are ready
  20984. */
  20985. Scene.prototype.isReady = function () {
  20986. if (this._isDisposed) {
  20987. return false;
  20988. }
  20989. if (this._pendingData.length > 0) {
  20990. return false;
  20991. }
  20992. var index;
  20993. var engine = this.getEngine();
  20994. // Geometries
  20995. for (index = 0; index < this._geometries.length; index++) {
  20996. var geometry = this._geometries[index];
  20997. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20998. return false;
  20999. }
  21000. }
  21001. // Meshes
  21002. for (index = 0; index < this.meshes.length; index++) {
  21003. var mesh = this.meshes[index];
  21004. if (!mesh.isEnabled()) {
  21005. continue;
  21006. }
  21007. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21008. continue;
  21009. }
  21010. if (!mesh.isReady()) {
  21011. return false;
  21012. }
  21013. // Highlight layers
  21014. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21015. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21016. var layer = _a[_i];
  21017. if (!layer.hasMesh(mesh)) {
  21018. continue;
  21019. }
  21020. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21021. var subMesh = _c[_b];
  21022. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21023. return false;
  21024. }
  21025. }
  21026. }
  21027. }
  21028. return true;
  21029. };
  21030. Scene.prototype.resetCachedMaterial = function () {
  21031. this._cachedMaterial = null;
  21032. this._cachedEffect = null;
  21033. this._cachedVisibility = null;
  21034. };
  21035. Scene.prototype.registerBeforeRender = function (func) {
  21036. this.onBeforeRenderObservable.add(func);
  21037. };
  21038. Scene.prototype.unregisterBeforeRender = function (func) {
  21039. this.onBeforeRenderObservable.removeCallback(func);
  21040. };
  21041. Scene.prototype.registerAfterRender = function (func) {
  21042. this.onAfterRenderObservable.add(func);
  21043. };
  21044. Scene.prototype.unregisterAfterRender = function (func) {
  21045. this.onAfterRenderObservable.removeCallback(func);
  21046. };
  21047. Scene.prototype._executeOnceBeforeRender = function (func) {
  21048. var _this = this;
  21049. var execFunc = function () {
  21050. func();
  21051. setTimeout(function () {
  21052. _this.unregisterBeforeRender(execFunc);
  21053. });
  21054. };
  21055. this.registerBeforeRender(execFunc);
  21056. };
  21057. /**
  21058. * The provided function will run before render once and will be disposed afterwards.
  21059. * A timeout delay can be provided so that the function will be executed in N ms.
  21060. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21061. * @param func The function to be executed.
  21062. * @param timeout optional delay in ms
  21063. */
  21064. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21065. var _this = this;
  21066. if (timeout !== undefined) {
  21067. setTimeout(function () {
  21068. _this._executeOnceBeforeRender(func);
  21069. }, timeout);
  21070. }
  21071. else {
  21072. this._executeOnceBeforeRender(func);
  21073. }
  21074. };
  21075. Scene.prototype._addPendingData = function (data) {
  21076. this._pendingData.push(data);
  21077. };
  21078. Scene.prototype._removePendingData = function (data) {
  21079. var wasLoading = this.isLoading;
  21080. var index = this._pendingData.indexOf(data);
  21081. if (index !== -1) {
  21082. this._pendingData.splice(index, 1);
  21083. }
  21084. if (wasLoading && !this.isLoading) {
  21085. this.onDataLoadedObservable.notifyObservers(this);
  21086. }
  21087. };
  21088. Scene.prototype.getWaitingItemsCount = function () {
  21089. return this._pendingData.length;
  21090. };
  21091. Object.defineProperty(Scene.prototype, "isLoading", {
  21092. get: function () {
  21093. return this._pendingData.length > 0;
  21094. },
  21095. enumerable: true,
  21096. configurable: true
  21097. });
  21098. /**
  21099. * Registers a function to be executed when the scene is ready.
  21100. * @param {Function} func - the function to be executed.
  21101. */
  21102. Scene.prototype.executeWhenReady = function (func) {
  21103. var _this = this;
  21104. this.onReadyObservable.add(func);
  21105. if (this._executeWhenReadyTimeoutId !== -1) {
  21106. return;
  21107. }
  21108. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21109. _this._checkIsReady();
  21110. }, 150);
  21111. };
  21112. Scene.prototype._checkIsReady = function () {
  21113. var _this = this;
  21114. if (this.isReady()) {
  21115. this.onReadyObservable.notifyObservers(this);
  21116. this.onReadyObservable.clear();
  21117. this._executeWhenReadyTimeoutId = -1;
  21118. return;
  21119. }
  21120. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21121. _this._checkIsReady();
  21122. }, 150);
  21123. };
  21124. // Animations
  21125. /**
  21126. * Will start the animation sequence of a given target
  21127. * @param target - the target
  21128. * @param {number} from - from which frame should animation start
  21129. * @param {number} to - till which frame should animation run.
  21130. * @param {boolean} [loop] - should the animation loop
  21131. * @param {number} [speedRatio] - the speed in which to run the animation
  21132. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21133. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21134. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21135. * See BABYLON.Animatable
  21136. */
  21137. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21138. if (speedRatio === void 0) { speedRatio = 1.0; }
  21139. if (from > to && speedRatio > 0) {
  21140. speedRatio *= -1;
  21141. }
  21142. this.stopAnimation(target);
  21143. if (!animatable) {
  21144. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21145. }
  21146. // Local animations
  21147. if (target.animations) {
  21148. animatable.appendAnimations(target, target.animations);
  21149. }
  21150. // Children animations
  21151. if (target.getAnimatables) {
  21152. var animatables = target.getAnimatables();
  21153. for (var index = 0; index < animatables.length; index++) {
  21154. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21155. }
  21156. }
  21157. animatable.reset();
  21158. return animatable;
  21159. };
  21160. /**
  21161. * Begin a new animation on a given node
  21162. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21163. * @param {BABYLON.Animation[]} defines the list of animations to start
  21164. * @param {number} from defines the initial value
  21165. * @param {number} to defines the final value
  21166. * @param {boolean} loop defines if you want animation to loop (off by default)
  21167. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21168. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21169. * @returns the list of created animatables
  21170. */
  21171. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21172. if (speedRatio === undefined) {
  21173. speedRatio = 1.0;
  21174. }
  21175. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21176. return animatable;
  21177. };
  21178. /**
  21179. * Begin a new animation on a given node and its hierarchy
  21180. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21181. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  21182. * @param {BABYLON.Animation[]} defines the list of animations to start
  21183. * @param {number} from defines the initial value
  21184. * @param {number} to defines the final value
  21185. * @param {boolean} loop defines if you want animation to loop (off by default)
  21186. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21187. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21188. * @returns the list of animatables created for all nodes
  21189. */
  21190. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21191. var children = target.getDescendants(directDescendantsOnly);
  21192. var result = [];
  21193. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21194. var child = children_1[_i];
  21195. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21196. }
  21197. return result;
  21198. };
  21199. Scene.prototype.getAnimatableByTarget = function (target) {
  21200. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21201. if (this._activeAnimatables[index].target === target) {
  21202. return this._activeAnimatables[index];
  21203. }
  21204. }
  21205. return null;
  21206. };
  21207. Object.defineProperty(Scene.prototype, "animatables", {
  21208. get: function () {
  21209. return this._activeAnimatables;
  21210. },
  21211. enumerable: true,
  21212. configurable: true
  21213. });
  21214. /**
  21215. * Will stop the animation of the given target
  21216. * @param target - the target
  21217. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21218. * @see beginAnimation
  21219. */
  21220. Scene.prototype.stopAnimation = function (target, animationName) {
  21221. var animatable = this.getAnimatableByTarget(target);
  21222. if (animatable) {
  21223. animatable.stop(animationName);
  21224. }
  21225. };
  21226. /**
  21227. * Stops and removes all animations that have been applied to the scene
  21228. */
  21229. Scene.prototype.stopAllAnimations = function () {
  21230. if (this._activeAnimatables) {
  21231. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21232. this._activeAnimatables[i].stop();
  21233. }
  21234. this._activeAnimatables = [];
  21235. }
  21236. };
  21237. Scene.prototype._animate = function () {
  21238. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21239. return;
  21240. }
  21241. // Getting time
  21242. var now = BABYLON.Tools.Now;
  21243. if (!this._animationTimeLast) {
  21244. if (this._pendingData.length > 0) {
  21245. return;
  21246. }
  21247. this._animationTimeLast = now;
  21248. }
  21249. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21250. this._animationTime += deltaTime;
  21251. this._animationTimeLast = now;
  21252. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21253. this._activeAnimatables[index]._animate(this._animationTime);
  21254. }
  21255. };
  21256. // Matrix
  21257. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21258. this._useAlternateCameraConfiguration = active;
  21259. };
  21260. Scene.prototype.getViewMatrix = function () {
  21261. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21262. };
  21263. Scene.prototype.getProjectionMatrix = function () {
  21264. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21265. };
  21266. Scene.prototype.getTransformMatrix = function () {
  21267. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21268. };
  21269. Scene.prototype.setTransformMatrix = function (view, projection) {
  21270. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21271. return;
  21272. }
  21273. this._viewUpdateFlag = view.updateFlag;
  21274. this._projectionUpdateFlag = projection.updateFlag;
  21275. this._viewMatrix = view;
  21276. this._projectionMatrix = projection;
  21277. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21278. // Update frustum
  21279. if (!this._frustumPlanes) {
  21280. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21281. }
  21282. else {
  21283. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21284. }
  21285. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21286. var otherCamera = this.activeCamera._alternateCamera;
  21287. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21288. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21289. }
  21290. if (this._sceneUbo.useUbo) {
  21291. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21292. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21293. this._sceneUbo.update();
  21294. }
  21295. };
  21296. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21297. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21298. return;
  21299. }
  21300. this._alternateViewUpdateFlag = view.updateFlag;
  21301. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21302. this._alternateViewMatrix = view;
  21303. this._alternateProjectionMatrix = projection;
  21304. if (!this._alternateTransformMatrix) {
  21305. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21306. }
  21307. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21308. if (!this._alternateSceneUbo) {
  21309. this._createAlternateUbo();
  21310. }
  21311. if (this._alternateSceneUbo.useUbo) {
  21312. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21313. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21314. this._alternateSceneUbo.update();
  21315. }
  21316. };
  21317. Scene.prototype.getSceneUniformBuffer = function () {
  21318. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21319. };
  21320. // Methods
  21321. Scene.prototype.getUniqueId = function () {
  21322. var result = Scene._uniqueIdCounter;
  21323. Scene._uniqueIdCounter++;
  21324. return result;
  21325. };
  21326. Scene.prototype.addMesh = function (newMesh) {
  21327. this.meshes.push(newMesh);
  21328. //notify the collision coordinator
  21329. if (this.collisionCoordinator) {
  21330. this.collisionCoordinator.onMeshAdded(newMesh);
  21331. }
  21332. newMesh._resyncLightSources();
  21333. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21334. };
  21335. Scene.prototype.removeMesh = function (toRemove) {
  21336. var index = this.meshes.indexOf(toRemove);
  21337. if (index !== -1) {
  21338. // Remove from the scene if mesh found
  21339. this.meshes.splice(index, 1);
  21340. }
  21341. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21342. return index;
  21343. };
  21344. Scene.prototype.addTransformNode = function (newTransformNode) {
  21345. this.transformNodes.push(newTransformNode);
  21346. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21347. };
  21348. Scene.prototype.removeTransformNode = function (toRemove) {
  21349. var index = this.transformNodes.indexOf(toRemove);
  21350. if (index !== -1) {
  21351. // Remove from the scene if found
  21352. this.transformNodes.splice(index, 1);
  21353. }
  21354. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21355. return index;
  21356. };
  21357. Scene.prototype.removeSkeleton = function (toRemove) {
  21358. var index = this.skeletons.indexOf(toRemove);
  21359. if (index !== -1) {
  21360. // Remove from the scene if found
  21361. this.skeletons.splice(index, 1);
  21362. }
  21363. return index;
  21364. };
  21365. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21366. var index = this.morphTargetManagers.indexOf(toRemove);
  21367. if (index !== -1) {
  21368. // Remove from the scene if found
  21369. this.morphTargetManagers.splice(index, 1);
  21370. }
  21371. return index;
  21372. };
  21373. Scene.prototype.removeLight = function (toRemove) {
  21374. var index = this.lights.indexOf(toRemove);
  21375. if (index !== -1) {
  21376. // Remove from meshes
  21377. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21378. var mesh = _a[_i];
  21379. mesh._removeLightSource(toRemove);
  21380. }
  21381. // Remove from the scene if mesh found
  21382. this.lights.splice(index, 1);
  21383. this.sortLightsByPriority();
  21384. }
  21385. this.onLightRemovedObservable.notifyObservers(toRemove);
  21386. return index;
  21387. };
  21388. Scene.prototype.removeCamera = function (toRemove) {
  21389. var index = this.cameras.indexOf(toRemove);
  21390. if (index !== -1) {
  21391. // Remove from the scene if mesh found
  21392. this.cameras.splice(index, 1);
  21393. }
  21394. // Remove from activeCameras
  21395. var index2 = this.activeCameras.indexOf(toRemove);
  21396. if (index2 !== -1) {
  21397. // Remove from the scene if mesh found
  21398. this.activeCameras.splice(index2, 1);
  21399. }
  21400. // Reset the activeCamera
  21401. if (this.activeCamera === toRemove) {
  21402. if (this.cameras.length > 0) {
  21403. this.activeCamera = this.cameras[0];
  21404. }
  21405. else {
  21406. this.activeCamera = null;
  21407. }
  21408. }
  21409. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21410. return index;
  21411. };
  21412. Scene.prototype.removeParticleSystem = function (toRemove) {
  21413. var index = this.particleSystems.indexOf(toRemove);
  21414. if (index !== -1) {
  21415. this.particleSystems.splice(index, 1);
  21416. }
  21417. return index;
  21418. };
  21419. ;
  21420. Scene.prototype.removeAnimation = function (toRemove) {
  21421. var index = this.animations.indexOf(toRemove);
  21422. if (index !== -1) {
  21423. this.animations.splice(index, 1);
  21424. }
  21425. return index;
  21426. };
  21427. ;
  21428. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21429. var index = this.multiMaterials.indexOf(toRemove);
  21430. if (index !== -1) {
  21431. this.multiMaterials.splice(index, 1);
  21432. }
  21433. return index;
  21434. };
  21435. ;
  21436. Scene.prototype.removeMaterial = function (toRemove) {
  21437. var index = this.materials.indexOf(toRemove);
  21438. if (index !== -1) {
  21439. this.materials.splice(index, 1);
  21440. }
  21441. return index;
  21442. };
  21443. ;
  21444. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21445. var index = this.lensFlareSystems.indexOf(toRemove);
  21446. if (index !== -1) {
  21447. this.lensFlareSystems.splice(index, 1);
  21448. }
  21449. return index;
  21450. };
  21451. ;
  21452. Scene.prototype.removeActionManager = function (toRemove) {
  21453. var index = this._actionManagers.indexOf(toRemove);
  21454. if (index !== -1) {
  21455. this._actionManagers.splice(index, 1);
  21456. }
  21457. return index;
  21458. };
  21459. ;
  21460. Scene.prototype.addLight = function (newLight) {
  21461. this.lights.push(newLight);
  21462. this.sortLightsByPriority();
  21463. // Add light to all meshes (To support if the light is removed and then readded)
  21464. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21465. var mesh = _a[_i];
  21466. if (mesh._lightSources.indexOf(newLight) === -1) {
  21467. mesh._lightSources.push(newLight);
  21468. mesh._resyncLightSources();
  21469. }
  21470. }
  21471. this.onNewLightAddedObservable.notifyObservers(newLight);
  21472. };
  21473. Scene.prototype.sortLightsByPriority = function () {
  21474. if (this.requireLightSorting) {
  21475. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21476. }
  21477. };
  21478. Scene.prototype.addCamera = function (newCamera) {
  21479. this.cameras.push(newCamera);
  21480. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21481. };
  21482. Scene.prototype.addSkeleton = function (newSkeleton) {
  21483. this.skeletons.push(newSkeleton);
  21484. };
  21485. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21486. this.particleSystems.push(newParticleSystem);
  21487. };
  21488. Scene.prototype.addAnimation = function (newAnimation) {
  21489. this.animations.push(newAnimation);
  21490. };
  21491. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21492. this.multiMaterials.push(newMultiMaterial);
  21493. };
  21494. Scene.prototype.addMaterial = function (newMaterial) {
  21495. this.materials.push(newMaterial);
  21496. };
  21497. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21498. this.morphTargetManagers.push(newMorphTargetManager);
  21499. };
  21500. Scene.prototype.addGeometry = function (newGeometrie) {
  21501. this._geometries.push(newGeometrie);
  21502. };
  21503. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21504. this.lensFlareSystems.push(newLensFlareSystem);
  21505. };
  21506. Scene.prototype.addActionManager = function (newActionManager) {
  21507. this._actionManagers.push(newActionManager);
  21508. };
  21509. /**
  21510. * Switch active camera
  21511. * @param {Camera} newCamera - new active camera
  21512. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21513. */
  21514. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21515. if (attachControl === void 0) { attachControl = true; }
  21516. var canvas = this._engine.getRenderingCanvas();
  21517. if (!canvas) {
  21518. return;
  21519. }
  21520. if (this.activeCamera) {
  21521. this.activeCamera.detachControl(canvas);
  21522. }
  21523. this.activeCamera = newCamera;
  21524. if (attachControl) {
  21525. newCamera.attachControl(canvas);
  21526. }
  21527. };
  21528. /**
  21529. * sets the active camera of the scene using its ID
  21530. * @param {string} id - the camera's ID
  21531. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21532. * @see activeCamera
  21533. */
  21534. Scene.prototype.setActiveCameraByID = function (id) {
  21535. var camera = this.getCameraByID(id);
  21536. if (camera) {
  21537. this.activeCamera = camera;
  21538. return camera;
  21539. }
  21540. return null;
  21541. };
  21542. /**
  21543. * sets the active camera of the scene using its name
  21544. * @param {string} name - the camera's name
  21545. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21546. * @see activeCamera
  21547. */
  21548. Scene.prototype.setActiveCameraByName = function (name) {
  21549. var camera = this.getCameraByName(name);
  21550. if (camera) {
  21551. this.activeCamera = camera;
  21552. return camera;
  21553. }
  21554. return null;
  21555. };
  21556. /**
  21557. * get an animation group using its name
  21558. * @param {string} the material's name
  21559. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21560. */
  21561. Scene.prototype.getAnimationGroupByName = function (name) {
  21562. for (var index = 0; index < this.animationGroups.length; index++) {
  21563. if (this.animationGroups[index].name === name) {
  21564. return this.animationGroups[index];
  21565. }
  21566. }
  21567. return null;
  21568. };
  21569. /**
  21570. * get a material using its id
  21571. * @param {string} the material's ID
  21572. * @return {BABYLON.Material|null} the material or null if none found.
  21573. */
  21574. Scene.prototype.getMaterialByID = function (id) {
  21575. for (var index = 0; index < this.materials.length; index++) {
  21576. if (this.materials[index].id === id) {
  21577. return this.materials[index];
  21578. }
  21579. }
  21580. return null;
  21581. };
  21582. /**
  21583. * get a material using its name
  21584. * @param {string} the material's name
  21585. * @return {BABYLON.Material|null} the material or null if none found.
  21586. */
  21587. Scene.prototype.getMaterialByName = function (name) {
  21588. for (var index = 0; index < this.materials.length; index++) {
  21589. if (this.materials[index].name === name) {
  21590. return this.materials[index];
  21591. }
  21592. }
  21593. return null;
  21594. };
  21595. Scene.prototype.getLensFlareSystemByName = function (name) {
  21596. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21597. if (this.lensFlareSystems[index].name === name) {
  21598. return this.lensFlareSystems[index];
  21599. }
  21600. }
  21601. return null;
  21602. };
  21603. Scene.prototype.getLensFlareSystemByID = function (id) {
  21604. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21605. if (this.lensFlareSystems[index].id === id) {
  21606. return this.lensFlareSystems[index];
  21607. }
  21608. }
  21609. return null;
  21610. };
  21611. Scene.prototype.getCameraByID = function (id) {
  21612. for (var index = 0; index < this.cameras.length; index++) {
  21613. if (this.cameras[index].id === id) {
  21614. return this.cameras[index];
  21615. }
  21616. }
  21617. return null;
  21618. };
  21619. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21620. for (var index = 0; index < this.cameras.length; index++) {
  21621. if (this.cameras[index].uniqueId === uniqueId) {
  21622. return this.cameras[index];
  21623. }
  21624. }
  21625. return null;
  21626. };
  21627. /**
  21628. * get a camera using its name
  21629. * @param {string} the camera's name
  21630. * @return {BABYLON.Camera|null} the camera or null if none found.
  21631. */
  21632. Scene.prototype.getCameraByName = function (name) {
  21633. for (var index = 0; index < this.cameras.length; index++) {
  21634. if (this.cameras[index].name === name) {
  21635. return this.cameras[index];
  21636. }
  21637. }
  21638. return null;
  21639. };
  21640. /**
  21641. * get a bone using its id
  21642. * @param {string} the bone's id
  21643. * @return {BABYLON.Bone|null} the bone or null if not found
  21644. */
  21645. Scene.prototype.getBoneByID = function (id) {
  21646. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21647. var skeleton = this.skeletons[skeletonIndex];
  21648. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21649. if (skeleton.bones[boneIndex].id === id) {
  21650. return skeleton.bones[boneIndex];
  21651. }
  21652. }
  21653. }
  21654. return null;
  21655. };
  21656. /**
  21657. * get a bone using its id
  21658. * @param {string} the bone's name
  21659. * @return {BABYLON.Bone|null} the bone or null if not found
  21660. */
  21661. Scene.prototype.getBoneByName = function (name) {
  21662. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21663. var skeleton = this.skeletons[skeletonIndex];
  21664. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21665. if (skeleton.bones[boneIndex].name === name) {
  21666. return skeleton.bones[boneIndex];
  21667. }
  21668. }
  21669. }
  21670. return null;
  21671. };
  21672. /**
  21673. * get a light node using its name
  21674. * @param {string} the light's name
  21675. * @return {BABYLON.Light|null} the light or null if none found.
  21676. */
  21677. Scene.prototype.getLightByName = function (name) {
  21678. for (var index = 0; index < this.lights.length; index++) {
  21679. if (this.lights[index].name === name) {
  21680. return this.lights[index];
  21681. }
  21682. }
  21683. return null;
  21684. };
  21685. /**
  21686. * get a light node using its ID
  21687. * @param {string} the light's id
  21688. * @return {BABYLON.Light|null} the light or null if none found.
  21689. */
  21690. Scene.prototype.getLightByID = function (id) {
  21691. for (var index = 0; index < this.lights.length; index++) {
  21692. if (this.lights[index].id === id) {
  21693. return this.lights[index];
  21694. }
  21695. }
  21696. return null;
  21697. };
  21698. /**
  21699. * get a light node using its scene-generated unique ID
  21700. * @param {number} the light's unique id
  21701. * @return {BABYLON.Light|null} the light or null if none found.
  21702. */
  21703. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21704. for (var index = 0; index < this.lights.length; index++) {
  21705. if (this.lights[index].uniqueId === uniqueId) {
  21706. return this.lights[index];
  21707. }
  21708. }
  21709. return null;
  21710. };
  21711. /**
  21712. * get a particle system by id
  21713. * @param id {number} the particle system id
  21714. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21715. */
  21716. Scene.prototype.getParticleSystemByID = function (id) {
  21717. for (var index = 0; index < this.particleSystems.length; index++) {
  21718. if (this.particleSystems[index].id === id) {
  21719. return this.particleSystems[index];
  21720. }
  21721. }
  21722. return null;
  21723. };
  21724. /**
  21725. * get a geometry using its ID
  21726. * @param {string} the geometry's id
  21727. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21728. */
  21729. Scene.prototype.getGeometryByID = function (id) {
  21730. for (var index = 0; index < this._geometries.length; index++) {
  21731. if (this._geometries[index].id === id) {
  21732. return this._geometries[index];
  21733. }
  21734. }
  21735. return null;
  21736. };
  21737. /**
  21738. * add a new geometry to this scene.
  21739. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21740. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21741. * @return {boolean} was the geometry added or not
  21742. */
  21743. Scene.prototype.pushGeometry = function (geometry, force) {
  21744. if (!force && this.getGeometryByID(geometry.id)) {
  21745. return false;
  21746. }
  21747. this._geometries.push(geometry);
  21748. //notify the collision coordinator
  21749. if (this.collisionCoordinator) {
  21750. this.collisionCoordinator.onGeometryAdded(geometry);
  21751. }
  21752. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21753. return true;
  21754. };
  21755. /**
  21756. * Removes an existing geometry
  21757. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21758. * @return {boolean} was the geometry removed or not
  21759. */
  21760. Scene.prototype.removeGeometry = function (geometry) {
  21761. var index = this._geometries.indexOf(geometry);
  21762. if (index > -1) {
  21763. this._geometries.splice(index, 1);
  21764. //notify the collision coordinator
  21765. if (this.collisionCoordinator) {
  21766. this.collisionCoordinator.onGeometryDeleted(geometry);
  21767. }
  21768. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21769. return true;
  21770. }
  21771. return false;
  21772. };
  21773. Scene.prototype.getGeometries = function () {
  21774. return this._geometries;
  21775. };
  21776. /**
  21777. * Get the first added mesh found of a given ID
  21778. * @param {string} id - the id to search for
  21779. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21780. */
  21781. Scene.prototype.getMeshByID = function (id) {
  21782. for (var index = 0; index < this.meshes.length; index++) {
  21783. if (this.meshes[index].id === id) {
  21784. return this.meshes[index];
  21785. }
  21786. }
  21787. return null;
  21788. };
  21789. Scene.prototype.getMeshesByID = function (id) {
  21790. return this.meshes.filter(function (m) {
  21791. return m.id === id;
  21792. });
  21793. };
  21794. /**
  21795. * Get the first added transform node found of a given ID
  21796. * @param {string} id - the id to search for
  21797. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21798. */
  21799. Scene.prototype.getTransformNodeByID = function (id) {
  21800. for (var index = 0; index < this.transformNodes.length; index++) {
  21801. if (this.transformNodes[index].id === id) {
  21802. return this.transformNodes[index];
  21803. }
  21804. }
  21805. return null;
  21806. };
  21807. Scene.prototype.getTransformNodesByID = function (id) {
  21808. return this.transformNodes.filter(function (m) {
  21809. return m.id === id;
  21810. });
  21811. };
  21812. /**
  21813. * Get a mesh with its auto-generated unique id
  21814. * @param {number} uniqueId - the unique id to search for
  21815. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21816. */
  21817. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21818. for (var index = 0; index < this.meshes.length; index++) {
  21819. if (this.meshes[index].uniqueId === uniqueId) {
  21820. return this.meshes[index];
  21821. }
  21822. }
  21823. return null;
  21824. };
  21825. /**
  21826. * Get a the last added mesh found of a given ID
  21827. * @param {string} id - the id to search for
  21828. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21829. */
  21830. Scene.prototype.getLastMeshByID = function (id) {
  21831. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21832. if (this.meshes[index].id === id) {
  21833. return this.meshes[index];
  21834. }
  21835. }
  21836. return null;
  21837. };
  21838. /**
  21839. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21840. * @param {string} id - the id to search for
  21841. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21842. */
  21843. Scene.prototype.getLastEntryByID = function (id) {
  21844. var index;
  21845. for (index = this.meshes.length - 1; index >= 0; index--) {
  21846. if (this.meshes[index].id === id) {
  21847. return this.meshes[index];
  21848. }
  21849. }
  21850. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21851. if (this.transformNodes[index].id === id) {
  21852. return this.transformNodes[index];
  21853. }
  21854. }
  21855. for (index = this.cameras.length - 1; index >= 0; index--) {
  21856. if (this.cameras[index].id === id) {
  21857. return this.cameras[index];
  21858. }
  21859. }
  21860. for (index = this.lights.length - 1; index >= 0; index--) {
  21861. if (this.lights[index].id === id) {
  21862. return this.lights[index];
  21863. }
  21864. }
  21865. return null;
  21866. };
  21867. Scene.prototype.getNodeByID = function (id) {
  21868. var mesh = this.getMeshByID(id);
  21869. if (mesh) {
  21870. return mesh;
  21871. }
  21872. var light = this.getLightByID(id);
  21873. if (light) {
  21874. return light;
  21875. }
  21876. var camera = this.getCameraByID(id);
  21877. if (camera) {
  21878. return camera;
  21879. }
  21880. var bone = this.getBoneByID(id);
  21881. return bone;
  21882. };
  21883. Scene.prototype.getNodeByName = function (name) {
  21884. var mesh = this.getMeshByName(name);
  21885. if (mesh) {
  21886. return mesh;
  21887. }
  21888. var light = this.getLightByName(name);
  21889. if (light) {
  21890. return light;
  21891. }
  21892. var camera = this.getCameraByName(name);
  21893. if (camera) {
  21894. return camera;
  21895. }
  21896. var bone = this.getBoneByName(name);
  21897. return bone;
  21898. };
  21899. Scene.prototype.getMeshByName = function (name) {
  21900. for (var index = 0; index < this.meshes.length; index++) {
  21901. if (this.meshes[index].name === name) {
  21902. return this.meshes[index];
  21903. }
  21904. }
  21905. return null;
  21906. };
  21907. Scene.prototype.getTransformNodeByName = function (name) {
  21908. for (var index = 0; index < this.transformNodes.length; index++) {
  21909. if (this.transformNodes[index].name === name) {
  21910. return this.transformNodes[index];
  21911. }
  21912. }
  21913. return null;
  21914. };
  21915. Scene.prototype.getSoundByName = function (name) {
  21916. var index;
  21917. if (BABYLON.AudioEngine) {
  21918. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21919. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21920. return this.mainSoundTrack.soundCollection[index];
  21921. }
  21922. }
  21923. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21924. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21925. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21926. return this.soundTracks[sdIndex].soundCollection[index];
  21927. }
  21928. }
  21929. }
  21930. }
  21931. return null;
  21932. };
  21933. Scene.prototype.getLastSkeletonByID = function (id) {
  21934. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21935. if (this.skeletons[index].id === id) {
  21936. return this.skeletons[index];
  21937. }
  21938. }
  21939. return null;
  21940. };
  21941. Scene.prototype.getSkeletonById = function (id) {
  21942. for (var index = 0; index < this.skeletons.length; index++) {
  21943. if (this.skeletons[index].id === id) {
  21944. return this.skeletons[index];
  21945. }
  21946. }
  21947. return null;
  21948. };
  21949. Scene.prototype.getSkeletonByName = function (name) {
  21950. for (var index = 0; index < this.skeletons.length; index++) {
  21951. if (this.skeletons[index].name === name) {
  21952. return this.skeletons[index];
  21953. }
  21954. }
  21955. return null;
  21956. };
  21957. Scene.prototype.getMorphTargetManagerById = function (id) {
  21958. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21959. if (this.morphTargetManagers[index].uniqueId === id) {
  21960. return this.morphTargetManagers[index];
  21961. }
  21962. }
  21963. return null;
  21964. };
  21965. Scene.prototype.isActiveMesh = function (mesh) {
  21966. return (this._activeMeshes.indexOf(mesh) !== -1);
  21967. };
  21968. /**
  21969. * Return a the first highlight layer of the scene with a given name.
  21970. * @param name The name of the highlight layer to look for.
  21971. * @return The highlight layer if found otherwise null.
  21972. */
  21973. Scene.prototype.getHighlightLayerByName = function (name) {
  21974. for (var index = 0; index < this.highlightLayers.length; index++) {
  21975. if (this.highlightLayers[index].name === name) {
  21976. return this.highlightLayers[index];
  21977. }
  21978. }
  21979. return null;
  21980. };
  21981. Object.defineProperty(Scene.prototype, "uid", {
  21982. /**
  21983. * Return a unique id as a string which can serve as an identifier for the scene
  21984. */
  21985. get: function () {
  21986. if (!this._uid) {
  21987. this._uid = BABYLON.Tools.RandomId();
  21988. }
  21989. return this._uid;
  21990. },
  21991. enumerable: true,
  21992. configurable: true
  21993. });
  21994. /**
  21995. * Add an externaly attached data from its key.
  21996. * This method call will fail and return false, if such key already exists.
  21997. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21998. * @param key the unique key that identifies the data
  21999. * @param data the data object to associate to the key for this Engine instance
  22000. * @return true if no such key were already present and the data was added successfully, false otherwise
  22001. */
  22002. Scene.prototype.addExternalData = function (key, data) {
  22003. if (!this._externalData) {
  22004. this._externalData = new BABYLON.StringDictionary();
  22005. }
  22006. return this._externalData.add(key, data);
  22007. };
  22008. /**
  22009. * Get an externaly attached data from its key
  22010. * @param key the unique key that identifies the data
  22011. * @return the associated data, if present (can be null), or undefined if not present
  22012. */
  22013. Scene.prototype.getExternalData = function (key) {
  22014. if (!this._externalData) {
  22015. return null;
  22016. }
  22017. return this._externalData.get(key);
  22018. };
  22019. /**
  22020. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22021. * @param key the unique key that identifies the data
  22022. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22023. * @return the associated data, can be null if the factory returned null.
  22024. */
  22025. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22026. if (!this._externalData) {
  22027. this._externalData = new BABYLON.StringDictionary();
  22028. }
  22029. return this._externalData.getOrAddWithFactory(key, factory);
  22030. };
  22031. /**
  22032. * Remove an externaly attached data from the Engine instance
  22033. * @param key the unique key that identifies the data
  22034. * @return true if the data was successfully removed, false if it doesn't exist
  22035. */
  22036. Scene.prototype.removeExternalData = function (key) {
  22037. return this._externalData.remove(key);
  22038. };
  22039. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22040. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22041. if (mesh.showSubMeshesBoundingBox) {
  22042. var boundingInfo = subMesh.getBoundingInfo();
  22043. if (boundingInfo !== null && boundingInfo !== undefined) {
  22044. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22045. }
  22046. }
  22047. var material = subMesh.getMaterial();
  22048. if (material !== null && material !== undefined) {
  22049. // Render targets
  22050. if (material.getRenderTargetTextures !== undefined) {
  22051. if (this._processedMaterials.indexOf(material) === -1) {
  22052. this._processedMaterials.push(material);
  22053. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22054. }
  22055. }
  22056. // Dispatch
  22057. this._activeIndices.addCount(subMesh.indexCount, false);
  22058. this._renderingManager.dispatch(subMesh, mesh, material);
  22059. }
  22060. }
  22061. };
  22062. Scene.prototype._isInIntermediateRendering = function () {
  22063. return this._intermediateRendering;
  22064. };
  22065. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22066. this._activeMeshCandidateProvider = provider;
  22067. };
  22068. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22069. return this._activeMeshCandidateProvider;
  22070. };
  22071. /**
  22072. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22073. */
  22074. Scene.prototype.freezeActiveMeshes = function () {
  22075. this._evaluateActiveMeshes();
  22076. this._activeMeshesFrozen = true;
  22077. return this;
  22078. };
  22079. /**
  22080. * Use this function to restart evaluating active meshes on every frame
  22081. */
  22082. Scene.prototype.unfreezeActiveMeshes = function () {
  22083. this._activeMeshesFrozen = false;
  22084. return this;
  22085. };
  22086. Scene.prototype._evaluateActiveMeshes = function () {
  22087. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22088. return;
  22089. }
  22090. if (!this.activeCamera) {
  22091. return;
  22092. }
  22093. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22094. this.activeCamera._activeMeshes.reset();
  22095. this._activeMeshes.reset();
  22096. this._renderingManager.reset();
  22097. this._processedMaterials.reset();
  22098. this._activeParticleSystems.reset();
  22099. this._activeSkeletons.reset();
  22100. this._softwareSkinnedMeshes.reset();
  22101. if (this._boundingBoxRenderer) {
  22102. this._boundingBoxRenderer.reset();
  22103. }
  22104. // Meshes
  22105. var meshes;
  22106. var len;
  22107. var checkIsEnabled = true;
  22108. // Determine mesh candidates
  22109. if (this._activeMeshCandidateProvider !== undefined) {
  22110. // Use _activeMeshCandidateProvider
  22111. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22112. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22113. if (meshes !== undefined) {
  22114. len = meshes.length;
  22115. }
  22116. else {
  22117. len = 0;
  22118. }
  22119. }
  22120. else if (this._selectionOctree !== undefined) {
  22121. // Octree
  22122. var selection = this._selectionOctree.select(this._frustumPlanes);
  22123. meshes = selection.data;
  22124. len = selection.length;
  22125. }
  22126. else {
  22127. // Full scene traversal
  22128. len = this.meshes.length;
  22129. meshes = this.meshes;
  22130. }
  22131. // Check each mesh
  22132. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22133. mesh = meshes[meshIndex];
  22134. if (mesh.isBlocked) {
  22135. continue;
  22136. }
  22137. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22138. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22139. continue;
  22140. }
  22141. mesh.computeWorldMatrix();
  22142. // Intersections
  22143. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22144. this._meshesForIntersections.pushNoDuplicate(mesh);
  22145. }
  22146. // Switch to current LOD
  22147. meshLOD = mesh.getLOD(this.activeCamera);
  22148. if (meshLOD === undefined || meshLOD === null) {
  22149. continue;
  22150. }
  22151. mesh._preActivate();
  22152. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22153. this._activeMeshes.push(mesh);
  22154. this.activeCamera._activeMeshes.push(mesh);
  22155. mesh._activate(this._renderId);
  22156. if (meshLOD !== mesh) {
  22157. meshLOD._activate(this._renderId);
  22158. }
  22159. this._activeMesh(mesh, meshLOD);
  22160. }
  22161. }
  22162. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22163. // Particle systems
  22164. if (this.particlesEnabled) {
  22165. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22166. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22167. var particleSystem = this.particleSystems[particleIndex];
  22168. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22169. continue;
  22170. }
  22171. var emitter = particleSystem.emitter;
  22172. if (!emitter.position || emitter.isEnabled()) {
  22173. this._activeParticleSystems.push(particleSystem);
  22174. particleSystem.animate();
  22175. this._renderingManager.dispatchParticles(particleSystem);
  22176. }
  22177. }
  22178. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22179. }
  22180. };
  22181. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22182. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22183. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22184. mesh.skeleton.prepare();
  22185. }
  22186. if (!mesh.computeBonesUsingShaders) {
  22187. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22188. }
  22189. }
  22190. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22191. var boundingInfo = sourceMesh.getBoundingInfo();
  22192. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22193. }
  22194. if (mesh !== undefined && mesh !== null
  22195. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22196. // Submeshes Octrees
  22197. var len;
  22198. var subMeshes;
  22199. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22200. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22201. len = intersections.length;
  22202. subMeshes = intersections.data;
  22203. }
  22204. else {
  22205. subMeshes = mesh.subMeshes;
  22206. len = subMeshes.length;
  22207. }
  22208. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22209. subMesh = subMeshes[subIndex];
  22210. this._evaluateSubMesh(subMesh, mesh);
  22211. }
  22212. }
  22213. };
  22214. Scene.prototype.updateTransformMatrix = function (force) {
  22215. if (!this.activeCamera) {
  22216. return;
  22217. }
  22218. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22219. };
  22220. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22221. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22222. };
  22223. Scene.prototype._renderForCamera = function (camera) {
  22224. if (camera && camera._skipRendering) {
  22225. return;
  22226. }
  22227. var engine = this._engine;
  22228. this.activeCamera = camera;
  22229. if (!this.activeCamera)
  22230. throw new Error("Active camera not set");
  22231. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22232. // Viewport
  22233. engine.setViewport(this.activeCamera.viewport);
  22234. // Camera
  22235. this.resetCachedMaterial();
  22236. this._renderId++;
  22237. this.activeCamera.update();
  22238. this.updateTransformMatrix();
  22239. if (camera._alternateCamera) {
  22240. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22241. this._alternateRendering = true;
  22242. }
  22243. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22244. // Meshes
  22245. this._evaluateActiveMeshes();
  22246. // Software skinning
  22247. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22248. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22249. mesh.applySkeleton(mesh.skeleton);
  22250. }
  22251. // Render targets
  22252. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22253. var needsRestoreFrameBuffer = false;
  22254. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22255. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22256. }
  22257. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22258. this._intermediateRendering = true;
  22259. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22260. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22261. var renderTarget = this._renderTargets.data[renderIndex];
  22262. if (renderTarget._shouldRender()) {
  22263. this._renderId++;
  22264. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22265. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22266. }
  22267. }
  22268. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22269. this._intermediateRendering = false;
  22270. this._renderId++;
  22271. needsRestoreFrameBuffer = true; // Restore back buffer
  22272. }
  22273. // Render HighlightLayer Texture
  22274. var stencilState = this._engine.getStencilBuffer();
  22275. var renderhighlights = false;
  22276. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22277. this._intermediateRendering = true;
  22278. for (var i = 0; i < this.highlightLayers.length; i++) {
  22279. var highlightLayer = this.highlightLayers[i];
  22280. if (highlightLayer.shouldRender() &&
  22281. (!highlightLayer.camera ||
  22282. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22283. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22284. renderhighlights = true;
  22285. var renderTarget = highlightLayer._mainTexture;
  22286. if (renderTarget._shouldRender()) {
  22287. this._renderId++;
  22288. renderTarget.render(false, false);
  22289. needsRestoreFrameBuffer = true;
  22290. }
  22291. }
  22292. }
  22293. this._intermediateRendering = false;
  22294. this._renderId++;
  22295. }
  22296. if (needsRestoreFrameBuffer) {
  22297. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22298. }
  22299. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22300. // Prepare Frame
  22301. this.postProcessManager._prepareFrame();
  22302. // Backgrounds
  22303. var layerIndex;
  22304. var layer;
  22305. if (this.layers.length) {
  22306. engine.setDepthBuffer(false);
  22307. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22308. layer = this.layers[layerIndex];
  22309. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22310. layer.render();
  22311. }
  22312. }
  22313. engine.setDepthBuffer(true);
  22314. }
  22315. // Activate HighlightLayer stencil
  22316. if (renderhighlights) {
  22317. this._engine.setStencilBuffer(true);
  22318. }
  22319. // Render
  22320. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22321. this._renderingManager.render(null, null, true, true);
  22322. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22323. // Restore HighlightLayer stencil
  22324. if (renderhighlights) {
  22325. this._engine.setStencilBuffer(stencilState);
  22326. }
  22327. // Bounding boxes
  22328. if (this._boundingBoxRenderer) {
  22329. this._boundingBoxRenderer.render();
  22330. }
  22331. // Lens flares
  22332. if (this.lensFlaresEnabled) {
  22333. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22334. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22335. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22336. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22337. lensFlareSystem.render();
  22338. }
  22339. }
  22340. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22341. }
  22342. // Foregrounds
  22343. if (this.layers.length) {
  22344. engine.setDepthBuffer(false);
  22345. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22346. layer = this.layers[layerIndex];
  22347. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22348. layer.render();
  22349. }
  22350. }
  22351. engine.setDepthBuffer(true);
  22352. }
  22353. // Highlight Layer
  22354. if (renderhighlights) {
  22355. engine.setDepthBuffer(false);
  22356. for (var i = 0; i < this.highlightLayers.length; i++) {
  22357. if (this.highlightLayers[i].shouldRender()) {
  22358. this.highlightLayers[i].render();
  22359. }
  22360. }
  22361. engine.setDepthBuffer(true);
  22362. }
  22363. // Finalize frame
  22364. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22365. // Reset some special arrays
  22366. this._renderTargets.reset();
  22367. this._alternateRendering = false;
  22368. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22369. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22370. };
  22371. Scene.prototype._processSubCameras = function (camera) {
  22372. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22373. this._renderForCamera(camera);
  22374. return;
  22375. }
  22376. // Update camera
  22377. if (this.activeCamera) {
  22378. this.activeCamera.update();
  22379. }
  22380. // rig cameras
  22381. for (var index = 0; index < camera._rigCameras.length; index++) {
  22382. this._renderForCamera(camera._rigCameras[index]);
  22383. }
  22384. this.activeCamera = camera;
  22385. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22386. };
  22387. Scene.prototype._checkIntersections = function () {
  22388. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22389. var sourceMesh = this._meshesForIntersections.data[index];
  22390. if (!sourceMesh.actionManager) {
  22391. continue;
  22392. }
  22393. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22394. var action = sourceMesh.actionManager.actions[actionIndex];
  22395. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22396. var parameters = action.getTriggerParameter();
  22397. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22398. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22399. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22400. if (areIntersecting && currentIntersectionInProgress === -1) {
  22401. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22402. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22403. sourceMesh._intersectionsInProgress.push(otherMesh);
  22404. }
  22405. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22406. sourceMesh._intersectionsInProgress.push(otherMesh);
  22407. }
  22408. }
  22409. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22410. //They intersected, and now they don't.
  22411. //is this trigger an exit trigger? execute an event.
  22412. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22413. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22414. }
  22415. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22416. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22417. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22418. }
  22419. }
  22420. }
  22421. }
  22422. }
  22423. };
  22424. Scene.prototype.render = function () {
  22425. if (this.isDisposed) {
  22426. return;
  22427. }
  22428. this._activeParticles.fetchNewFrame();
  22429. this._totalVertices.fetchNewFrame();
  22430. this._activeIndices.fetchNewFrame();
  22431. this._activeBones.fetchNewFrame();
  22432. this._meshesForIntersections.reset();
  22433. this.resetCachedMaterial();
  22434. this.onBeforeAnimationsObservable.notifyObservers(this);
  22435. // Actions
  22436. if (this.actionManager) {
  22437. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22438. }
  22439. //Simplification Queue
  22440. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22441. this.simplificationQueue.executeNext();
  22442. }
  22443. if (this._engine.isDeterministicLockStep()) {
  22444. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22445. var defaultFPS = (60.0 / 1000.0);
  22446. var defaultFrameTime = 1000 / 60; // frame time in MS
  22447. if (this._physicsEngine) {
  22448. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22449. }
  22450. var stepsTaken = 0;
  22451. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22452. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22453. internalSteps = Math.min(internalSteps, maxSubSteps);
  22454. do {
  22455. this.onBeforeStepObservable.notifyObservers(this);
  22456. // Animations
  22457. this._animationRatio = defaultFrameTime * defaultFPS;
  22458. this._animate();
  22459. this.onAfterAnimationsObservable.notifyObservers(this);
  22460. // Physics
  22461. if (this._physicsEngine) {
  22462. this.onBeforePhysicsObservable.notifyObservers(this);
  22463. this._physicsEngine._step(defaultFrameTime / 1000);
  22464. this.onAfterPhysicsObservable.notifyObservers(this);
  22465. }
  22466. this.onAfterStepObservable.notifyObservers(this);
  22467. this._currentStepId++;
  22468. stepsTaken++;
  22469. deltaTime -= defaultFrameTime;
  22470. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22471. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22472. }
  22473. else {
  22474. // Animations
  22475. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22476. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22477. this._animate();
  22478. this.onAfterAnimationsObservable.notifyObservers(this);
  22479. // Physics
  22480. if (this._physicsEngine) {
  22481. this.onBeforePhysicsObservable.notifyObservers(this);
  22482. this._physicsEngine._step(deltaTime / 1000.0);
  22483. this.onAfterPhysicsObservable.notifyObservers(this);
  22484. }
  22485. }
  22486. // update gamepad manager
  22487. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22488. this._gamepadManager._checkGamepadsStatus();
  22489. }
  22490. // Before render
  22491. this.onBeforeRenderObservable.notifyObservers(this);
  22492. // Customs render targets
  22493. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22494. var engine = this.getEngine();
  22495. var currentActiveCamera = this.activeCamera;
  22496. if (this.renderTargetsEnabled) {
  22497. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22498. this._intermediateRendering = true;
  22499. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22500. var renderTarget = this.customRenderTargets[customIndex];
  22501. if (renderTarget._shouldRender()) {
  22502. this._renderId++;
  22503. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22504. if (!this.activeCamera)
  22505. throw new Error("Active camera not set");
  22506. // Viewport
  22507. engine.setViewport(this.activeCamera.viewport);
  22508. // Camera
  22509. this.updateTransformMatrix();
  22510. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22511. }
  22512. }
  22513. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22514. this._intermediateRendering = false;
  22515. this._renderId++;
  22516. }
  22517. // Restore back buffer
  22518. if (this.customRenderTargets.length > 0) {
  22519. engine.restoreDefaultFramebuffer();
  22520. }
  22521. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22522. this.activeCamera = currentActiveCamera;
  22523. // Procedural textures
  22524. if (this.proceduralTexturesEnabled) {
  22525. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22526. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22527. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22528. if (proceduralTexture._shouldRender()) {
  22529. proceduralTexture.render();
  22530. }
  22531. }
  22532. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22533. }
  22534. // Clear
  22535. if (this.autoClearDepthAndStencil || this.autoClear) {
  22536. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22537. }
  22538. // Shadows
  22539. if (this.shadowsEnabled) {
  22540. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22541. var light = this.lights[lightIndex];
  22542. var shadowGenerator = light.getShadowGenerator();
  22543. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22544. var shadowMap = (shadowGenerator.getShadowMap());
  22545. if (this.textures.indexOf(shadowMap) !== -1) {
  22546. this._renderTargets.push(shadowMap);
  22547. }
  22548. }
  22549. }
  22550. }
  22551. // Depth renderer
  22552. if (this._depthRenderer) {
  22553. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22554. }
  22555. // Geometry renderer
  22556. if (this._geometryBufferRenderer) {
  22557. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22558. }
  22559. // RenderPipeline
  22560. if (this._postProcessRenderPipelineManager) {
  22561. this._postProcessRenderPipelineManager.update();
  22562. }
  22563. // Multi-cameras?
  22564. if (this.activeCameras.length > 0) {
  22565. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22566. if (cameraIndex > 0) {
  22567. this._engine.clear(null, false, true, true);
  22568. }
  22569. this._processSubCameras(this.activeCameras[cameraIndex]);
  22570. }
  22571. }
  22572. else {
  22573. if (!this.activeCamera) {
  22574. throw new Error("No camera defined");
  22575. }
  22576. this._processSubCameras(this.activeCamera);
  22577. }
  22578. // Intersection checks
  22579. this._checkIntersections();
  22580. // Update the audio listener attached to the camera
  22581. if (BABYLON.AudioEngine) {
  22582. this._updateAudioParameters();
  22583. }
  22584. // After render
  22585. if (this.afterRender) {
  22586. this.afterRender();
  22587. }
  22588. this.onAfterRenderObservable.notifyObservers(this);
  22589. // Cleaning
  22590. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22591. var data = this._toBeDisposed.data[index];
  22592. if (data) {
  22593. data.dispose();
  22594. }
  22595. this._toBeDisposed[index] = null;
  22596. }
  22597. this._toBeDisposed.reset();
  22598. if (this.dumpNextRenderTargets) {
  22599. this.dumpNextRenderTargets = false;
  22600. }
  22601. this._activeBones.addCount(0, true);
  22602. this._activeIndices.addCount(0, true);
  22603. this._activeParticles.addCount(0, true);
  22604. };
  22605. Scene.prototype._updateAudioParameters = function () {
  22606. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22607. return;
  22608. }
  22609. var listeningCamera;
  22610. var audioEngine = BABYLON.Engine.audioEngine;
  22611. if (this.activeCameras.length > 0) {
  22612. listeningCamera = this.activeCameras[0];
  22613. }
  22614. else {
  22615. listeningCamera = this.activeCamera;
  22616. }
  22617. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22618. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22619. // for VR cameras
  22620. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22621. listeningCamera = listeningCamera.rigCameras[0];
  22622. }
  22623. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22624. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22625. cameraDirection.normalize();
  22626. // To avoid some errors on GearVR
  22627. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22628. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22629. }
  22630. var i;
  22631. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22632. var sound = this.mainSoundTrack.soundCollection[i];
  22633. if (sound.useCustomAttenuation) {
  22634. sound.updateDistanceFromListener();
  22635. }
  22636. }
  22637. for (i = 0; i < this.soundTracks.length; i++) {
  22638. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22639. sound = this.soundTracks[i].soundCollection[j];
  22640. if (sound.useCustomAttenuation) {
  22641. sound.updateDistanceFromListener();
  22642. }
  22643. }
  22644. }
  22645. }
  22646. };
  22647. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22648. // Audio
  22649. get: function () {
  22650. return this._audioEnabled;
  22651. },
  22652. set: function (value) {
  22653. this._audioEnabled = value;
  22654. if (BABYLON.AudioEngine) {
  22655. if (this._audioEnabled) {
  22656. this._enableAudio();
  22657. }
  22658. else {
  22659. this._disableAudio();
  22660. }
  22661. }
  22662. },
  22663. enumerable: true,
  22664. configurable: true
  22665. });
  22666. Scene.prototype._disableAudio = function () {
  22667. var i;
  22668. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22669. this.mainSoundTrack.soundCollection[i].pause();
  22670. }
  22671. for (i = 0; i < this.soundTracks.length; i++) {
  22672. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22673. this.soundTracks[i].soundCollection[j].pause();
  22674. }
  22675. }
  22676. };
  22677. Scene.prototype._enableAudio = function () {
  22678. var i;
  22679. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22680. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22681. this.mainSoundTrack.soundCollection[i].play();
  22682. }
  22683. }
  22684. for (i = 0; i < this.soundTracks.length; i++) {
  22685. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22686. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22687. this.soundTracks[i].soundCollection[j].play();
  22688. }
  22689. }
  22690. }
  22691. };
  22692. Object.defineProperty(Scene.prototype, "headphone", {
  22693. get: function () {
  22694. return this._headphone;
  22695. },
  22696. set: function (value) {
  22697. this._headphone = value;
  22698. if (BABYLON.AudioEngine) {
  22699. if (this._headphone) {
  22700. this._switchAudioModeForHeadphones();
  22701. }
  22702. else {
  22703. this._switchAudioModeForNormalSpeakers();
  22704. }
  22705. }
  22706. },
  22707. enumerable: true,
  22708. configurable: true
  22709. });
  22710. Scene.prototype._switchAudioModeForHeadphones = function () {
  22711. this.mainSoundTrack.switchPanningModelToHRTF();
  22712. for (var i = 0; i < this.soundTracks.length; i++) {
  22713. this.soundTracks[i].switchPanningModelToHRTF();
  22714. }
  22715. };
  22716. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22717. this.mainSoundTrack.switchPanningModelToEqualPower();
  22718. for (var i = 0; i < this.soundTracks.length; i++) {
  22719. this.soundTracks[i].switchPanningModelToEqualPower();
  22720. }
  22721. };
  22722. Scene.prototype.enableDepthRenderer = function () {
  22723. if (this._depthRenderer) {
  22724. return this._depthRenderer;
  22725. }
  22726. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22727. return this._depthRenderer;
  22728. };
  22729. Scene.prototype.disableDepthRenderer = function () {
  22730. if (!this._depthRenderer) {
  22731. return;
  22732. }
  22733. this._depthRenderer.dispose();
  22734. this._depthRenderer = null;
  22735. };
  22736. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22737. if (ratio === void 0) { ratio = 1; }
  22738. if (this._geometryBufferRenderer) {
  22739. return this._geometryBufferRenderer;
  22740. }
  22741. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22742. if (!this._geometryBufferRenderer.isSupported) {
  22743. this._geometryBufferRenderer = null;
  22744. }
  22745. return this._geometryBufferRenderer;
  22746. };
  22747. Scene.prototype.disableGeometryBufferRenderer = function () {
  22748. if (!this._geometryBufferRenderer) {
  22749. return;
  22750. }
  22751. this._geometryBufferRenderer.dispose();
  22752. this._geometryBufferRenderer = null;
  22753. };
  22754. Scene.prototype.freezeMaterials = function () {
  22755. for (var i = 0; i < this.materials.length; i++) {
  22756. this.materials[i].freeze();
  22757. }
  22758. };
  22759. Scene.prototype.unfreezeMaterials = function () {
  22760. for (var i = 0; i < this.materials.length; i++) {
  22761. this.materials[i].unfreeze();
  22762. }
  22763. };
  22764. Scene.prototype.dispose = function () {
  22765. this.beforeRender = null;
  22766. this.afterRender = null;
  22767. this.skeletons = [];
  22768. this.morphTargetManagers = [];
  22769. this.importedMeshesFiles = new Array();
  22770. this.stopAllAnimations();
  22771. this.resetCachedMaterial();
  22772. if (this._depthRenderer) {
  22773. this._depthRenderer.dispose();
  22774. }
  22775. if (this._gamepadManager) {
  22776. this._gamepadManager.dispose();
  22777. this._gamepadManager = null;
  22778. }
  22779. // Smart arrays
  22780. if (this.activeCamera) {
  22781. this.activeCamera._activeMeshes.dispose();
  22782. this.activeCamera = null;
  22783. }
  22784. this._activeMeshes.dispose();
  22785. this._renderingManager.dispose();
  22786. this._processedMaterials.dispose();
  22787. this._activeParticleSystems.dispose();
  22788. this._activeSkeletons.dispose();
  22789. this._softwareSkinnedMeshes.dispose();
  22790. this._renderTargets.dispose();
  22791. if (this._boundingBoxRenderer) {
  22792. this._boundingBoxRenderer.dispose();
  22793. }
  22794. this._meshesForIntersections.dispose();
  22795. this._toBeDisposed.dispose();
  22796. // Abort active requests
  22797. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22798. var request = _a[_i];
  22799. request.abort();
  22800. }
  22801. // Debug layer
  22802. if (this._debugLayer) {
  22803. this._debugLayer.hide();
  22804. }
  22805. // Events
  22806. this.onDisposeObservable.notifyObservers(this);
  22807. this.onDisposeObservable.clear();
  22808. this.onBeforeRenderObservable.clear();
  22809. this.onAfterRenderObservable.clear();
  22810. this.OnBeforeRenderTargetsRenderObservable.clear();
  22811. this.OnAfterRenderTargetsRenderObservable.clear();
  22812. this.onAfterStepObservable.clear();
  22813. this.onBeforeStepObservable.clear();
  22814. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22815. this.onAfterActiveMeshesEvaluationObservable.clear();
  22816. this.onBeforeParticlesRenderingObservable.clear();
  22817. this.onAfterParticlesRenderingObservable.clear();
  22818. this.onBeforeSpritesRenderingObservable.clear();
  22819. this.onAfterSpritesRenderingObservable.clear();
  22820. this.onBeforeDrawPhaseObservable.clear();
  22821. this.onAfterDrawPhaseObservable.clear();
  22822. this.onBeforePhysicsObservable.clear();
  22823. this.onAfterPhysicsObservable.clear();
  22824. this.onBeforeAnimationsObservable.clear();
  22825. this.onAfterAnimationsObservable.clear();
  22826. this.onDataLoadedObservable.clear();
  22827. this.detachControl();
  22828. // Release sounds & sounds tracks
  22829. if (BABYLON.AudioEngine) {
  22830. this.disposeSounds();
  22831. }
  22832. // VR Helper
  22833. if (this.VRHelper) {
  22834. this.VRHelper.dispose();
  22835. }
  22836. // Detach cameras
  22837. var canvas = this._engine.getRenderingCanvas();
  22838. if (canvas) {
  22839. var index;
  22840. for (index = 0; index < this.cameras.length; index++) {
  22841. this.cameras[index].detachControl(canvas);
  22842. }
  22843. }
  22844. // Release animation groups
  22845. while (this.animationGroups.length) {
  22846. this.animationGroups[0].dispose();
  22847. }
  22848. // Release lights
  22849. while (this.lights.length) {
  22850. this.lights[0].dispose();
  22851. }
  22852. // Release meshes
  22853. while (this.meshes.length) {
  22854. this.meshes[0].dispose(true);
  22855. }
  22856. while (this.transformNodes.length) {
  22857. this.removeTransformNode(this.transformNodes[0]);
  22858. }
  22859. // Release cameras
  22860. while (this.cameras.length) {
  22861. this.cameras[0].dispose();
  22862. }
  22863. // Release materials
  22864. if (this.defaultMaterial) {
  22865. this.defaultMaterial.dispose();
  22866. }
  22867. while (this.multiMaterials.length) {
  22868. this.multiMaterials[0].dispose();
  22869. }
  22870. while (this.materials.length) {
  22871. this.materials[0].dispose();
  22872. }
  22873. // Release particles
  22874. while (this.particleSystems.length) {
  22875. this.particleSystems[0].dispose();
  22876. }
  22877. // Release sprites
  22878. while (this.spriteManagers.length) {
  22879. this.spriteManagers[0].dispose();
  22880. }
  22881. // Release postProcesses
  22882. while (this.postProcesses.length) {
  22883. this.postProcesses[0].dispose();
  22884. }
  22885. // Release layers
  22886. while (this.layers.length) {
  22887. this.layers[0].dispose();
  22888. }
  22889. while (this.highlightLayers.length) {
  22890. this.highlightLayers[0].dispose();
  22891. }
  22892. // Release textures
  22893. while (this.textures.length) {
  22894. this.textures[0].dispose();
  22895. }
  22896. // Release UBO
  22897. this._sceneUbo.dispose();
  22898. if (this._alternateSceneUbo) {
  22899. this._alternateSceneUbo.dispose();
  22900. }
  22901. // Post-processes
  22902. this.postProcessManager.dispose();
  22903. if (this._postProcessRenderPipelineManager) {
  22904. this._postProcessRenderPipelineManager.dispose();
  22905. }
  22906. // Physics
  22907. if (this._physicsEngine) {
  22908. this.disablePhysicsEngine();
  22909. }
  22910. // Remove from engine
  22911. index = this._engine.scenes.indexOf(this);
  22912. if (index > -1) {
  22913. this._engine.scenes.splice(index, 1);
  22914. }
  22915. this._engine.wipeCaches(true);
  22916. this._isDisposed = true;
  22917. };
  22918. Object.defineProperty(Scene.prototype, "isDisposed", {
  22919. get: function () {
  22920. return this._isDisposed;
  22921. },
  22922. enumerable: true,
  22923. configurable: true
  22924. });
  22925. // Release sounds & sounds tracks
  22926. Scene.prototype.disposeSounds = function () {
  22927. if (!this._mainSoundTrack) {
  22928. return;
  22929. }
  22930. this.mainSoundTrack.dispose();
  22931. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22932. this.soundTracks[scIndex].dispose();
  22933. }
  22934. };
  22935. // Octrees
  22936. Scene.prototype.getWorldExtends = function () {
  22937. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22938. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22939. for (var index = 0; index < this.meshes.length; index++) {
  22940. var mesh = this.meshes[index];
  22941. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22942. continue;
  22943. }
  22944. mesh.computeWorldMatrix(true);
  22945. var boundingInfo = mesh.getBoundingInfo();
  22946. var minBox = boundingInfo.boundingBox.minimumWorld;
  22947. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22948. BABYLON.Tools.CheckExtends(minBox, min, max);
  22949. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22950. }
  22951. return {
  22952. min: min,
  22953. max: max
  22954. };
  22955. };
  22956. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22957. if (maxCapacity === void 0) { maxCapacity = 64; }
  22958. if (maxDepth === void 0) { maxDepth = 2; }
  22959. if (!this._selectionOctree) {
  22960. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22961. }
  22962. var worldExtends = this.getWorldExtends();
  22963. // Update octree
  22964. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22965. return this._selectionOctree;
  22966. };
  22967. // Picking
  22968. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22969. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22970. var result = BABYLON.Ray.Zero();
  22971. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22972. return result;
  22973. };
  22974. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22975. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22976. var engine = this._engine;
  22977. if (!camera) {
  22978. if (!this.activeCamera)
  22979. throw new Error("Active camera not set");
  22980. camera = this.activeCamera;
  22981. }
  22982. var cameraViewport = camera.viewport;
  22983. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22984. // Moving coordinates to local viewport world
  22985. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22986. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22987. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22988. return this;
  22989. };
  22990. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22991. var result = BABYLON.Ray.Zero();
  22992. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22993. return result;
  22994. };
  22995. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22996. if (!BABYLON.PickingInfo) {
  22997. return this;
  22998. }
  22999. var engine = this._engine;
  23000. if (!camera) {
  23001. if (!this.activeCamera)
  23002. throw new Error("Active camera not set");
  23003. camera = this.activeCamera;
  23004. }
  23005. var cameraViewport = camera.viewport;
  23006. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23007. var identity = BABYLON.Matrix.Identity();
  23008. // Moving coordinates to local viewport world
  23009. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23010. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23011. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23012. return this;
  23013. };
  23014. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23015. if (!BABYLON.PickingInfo) {
  23016. return null;
  23017. }
  23018. var pickingInfo = null;
  23019. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23020. var mesh = this.meshes[meshIndex];
  23021. if (predicate) {
  23022. if (!predicate(mesh)) {
  23023. continue;
  23024. }
  23025. }
  23026. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23027. continue;
  23028. }
  23029. var world = mesh.getWorldMatrix();
  23030. var ray = rayFunction(world);
  23031. var result = mesh.intersects(ray, fastCheck);
  23032. if (!result || !result.hit)
  23033. continue;
  23034. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23035. continue;
  23036. pickingInfo = result;
  23037. if (fastCheck) {
  23038. break;
  23039. }
  23040. }
  23041. return pickingInfo || new BABYLON.PickingInfo();
  23042. };
  23043. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23044. if (!BABYLON.PickingInfo) {
  23045. return null;
  23046. }
  23047. var pickingInfos = new Array();
  23048. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23049. var mesh = this.meshes[meshIndex];
  23050. if (predicate) {
  23051. if (!predicate(mesh)) {
  23052. continue;
  23053. }
  23054. }
  23055. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23056. continue;
  23057. }
  23058. var world = mesh.getWorldMatrix();
  23059. var ray = rayFunction(world);
  23060. var result = mesh.intersects(ray, false);
  23061. if (!result || !result.hit)
  23062. continue;
  23063. pickingInfos.push(result);
  23064. }
  23065. return pickingInfos;
  23066. };
  23067. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23068. if (!BABYLON.PickingInfo) {
  23069. return null;
  23070. }
  23071. var pickingInfo = null;
  23072. if (!camera) {
  23073. if (!this.activeCamera) {
  23074. return null;
  23075. }
  23076. camera = this.activeCamera;
  23077. }
  23078. if (this.spriteManagers.length > 0) {
  23079. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23080. var spriteManager = this.spriteManagers[spriteIndex];
  23081. if (!spriteManager.isPickable) {
  23082. continue;
  23083. }
  23084. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23085. if (!result || !result.hit)
  23086. continue;
  23087. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23088. continue;
  23089. pickingInfo = result;
  23090. if (fastCheck) {
  23091. break;
  23092. }
  23093. }
  23094. }
  23095. return pickingInfo || new BABYLON.PickingInfo();
  23096. };
  23097. /** Launch a ray to try to pick a mesh in the scene
  23098. * @param x position on screen
  23099. * @param y position on screen
  23100. * @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
  23101. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23102. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23103. */
  23104. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23105. var _this = this;
  23106. if (!BABYLON.PickingInfo) {
  23107. return null;
  23108. }
  23109. return this._internalPick(function (world) {
  23110. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23111. return _this._tempPickingRay;
  23112. }, predicate, fastCheck);
  23113. };
  23114. /** Launch a ray to try to pick a sprite in the scene
  23115. * @param x position on screen
  23116. * @param y position on screen
  23117. * @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
  23118. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23119. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23120. */
  23121. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23122. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23123. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23124. };
  23125. /** Use the given ray to pick a mesh in the scene
  23126. * @param ray The ray to use to pick meshes
  23127. * @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
  23128. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23129. */
  23130. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23131. var _this = this;
  23132. return this._internalPick(function (world) {
  23133. if (!_this._pickWithRayInverseMatrix) {
  23134. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23135. }
  23136. world.invertToRef(_this._pickWithRayInverseMatrix);
  23137. if (!_this._cachedRayForTransform) {
  23138. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23139. }
  23140. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23141. return _this._cachedRayForTransform;
  23142. }, predicate, fastCheck);
  23143. };
  23144. /**
  23145. * Launch a ray to try to pick a mesh in the scene
  23146. * @param x X position on screen
  23147. * @param y Y position on screen
  23148. * @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
  23149. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23150. */
  23151. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23152. var _this = this;
  23153. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23154. };
  23155. /**
  23156. * Launch a ray to try to pick a mesh in the scene
  23157. * @param ray Ray to use
  23158. * @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
  23159. */
  23160. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23161. var _this = this;
  23162. return this._internalMultiPick(function (world) {
  23163. if (!_this._pickWithRayInverseMatrix) {
  23164. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23165. }
  23166. world.invertToRef(_this._pickWithRayInverseMatrix);
  23167. if (!_this._cachedRayForTransform) {
  23168. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23169. }
  23170. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23171. return _this._cachedRayForTransform;
  23172. }, predicate);
  23173. };
  23174. Scene.prototype.setPointerOverMesh = function (mesh) {
  23175. if (this._pointerOverMesh === mesh) {
  23176. return;
  23177. }
  23178. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23179. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23180. }
  23181. this._pointerOverMesh = mesh;
  23182. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23183. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23184. }
  23185. };
  23186. Scene.prototype.getPointerOverMesh = function () {
  23187. return this._pointerOverMesh;
  23188. };
  23189. Scene.prototype.setPointerOverSprite = function (sprite) {
  23190. if (this._pointerOverSprite === sprite) {
  23191. return;
  23192. }
  23193. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23194. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23195. }
  23196. this._pointerOverSprite = sprite;
  23197. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23198. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23199. }
  23200. };
  23201. Scene.prototype.getPointerOverSprite = function () {
  23202. return this._pointerOverSprite;
  23203. };
  23204. // Physics
  23205. Scene.prototype.getPhysicsEngine = function () {
  23206. return this._physicsEngine;
  23207. };
  23208. /**
  23209. * Enables physics to the current scene
  23210. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23211. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23212. * @return {boolean} was the physics engine initialized
  23213. */
  23214. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23215. if (gravity === void 0) { gravity = null; }
  23216. if (this._physicsEngine) {
  23217. return true;
  23218. }
  23219. try {
  23220. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23221. return true;
  23222. }
  23223. catch (e) {
  23224. BABYLON.Tools.Error(e.message);
  23225. return false;
  23226. }
  23227. };
  23228. Scene.prototype.disablePhysicsEngine = function () {
  23229. if (!this._physicsEngine) {
  23230. return;
  23231. }
  23232. this._physicsEngine.dispose();
  23233. this._physicsEngine = null;
  23234. };
  23235. Scene.prototype.isPhysicsEnabled = function () {
  23236. return this._physicsEngine !== undefined;
  23237. };
  23238. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23239. var mesh = compound.parts[0].mesh;
  23240. if (mesh.physicsImpostor) {
  23241. mesh.physicsImpostor.dispose();
  23242. mesh.physicsImpostor = null;
  23243. }
  23244. };
  23245. // Misc.
  23246. Scene.prototype._rebuildGeometries = function () {
  23247. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23248. var geometry = _a[_i];
  23249. geometry._rebuild();
  23250. }
  23251. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23252. var mesh = _c[_b];
  23253. mesh._rebuild();
  23254. }
  23255. if (this.postProcessManager) {
  23256. this.postProcessManager._rebuild();
  23257. }
  23258. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23259. var layer = _e[_d];
  23260. layer._rebuild();
  23261. }
  23262. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23263. var highlightLayer = _g[_f];
  23264. highlightLayer._rebuild();
  23265. }
  23266. if (this._boundingBoxRenderer) {
  23267. this._boundingBoxRenderer._rebuild();
  23268. }
  23269. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23270. var system = _j[_h];
  23271. system.rebuild();
  23272. }
  23273. if (this._postProcessRenderPipelineManager) {
  23274. this._postProcessRenderPipelineManager._rebuild();
  23275. }
  23276. };
  23277. Scene.prototype._rebuildTextures = function () {
  23278. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23279. var texture = _a[_i];
  23280. texture._rebuild();
  23281. }
  23282. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23283. };
  23284. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23285. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23286. if (replace === void 0) { replace = false; }
  23287. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23288. // Dispose existing camera or light in replace mode.
  23289. if (replace) {
  23290. if (this.activeCamera) {
  23291. this.activeCamera.dispose();
  23292. this.activeCamera = null;
  23293. }
  23294. if (this.lights) {
  23295. for (var i = 0; i < this.lights.length; i++) {
  23296. this.lights[i].dispose();
  23297. }
  23298. }
  23299. }
  23300. // Light
  23301. if (this.lights.length === 0) {
  23302. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23303. }
  23304. // Camera
  23305. if (!this.activeCamera) {
  23306. var worldExtends = this.getWorldExtends();
  23307. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23308. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23309. var camera;
  23310. var radius = worldSize.length() * 1.5;
  23311. if (createArcRotateCamera) {
  23312. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23313. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23314. arcRotateCamera.wheelPrecision = 100 / radius;
  23315. camera = arcRotateCamera;
  23316. }
  23317. else {
  23318. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23319. freeCamera.setTarget(worldCenter);
  23320. camera = freeCamera;
  23321. }
  23322. camera.minZ = radius * 0.01;
  23323. camera.maxZ = radius * 1000;
  23324. camera.speed = radius * 0.2;
  23325. this.activeCamera = camera;
  23326. var canvas = this.getEngine().getRenderingCanvas();
  23327. if (attachCameraControls && canvas) {
  23328. camera.attachControl(canvas);
  23329. }
  23330. }
  23331. };
  23332. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23333. if (pbr === void 0) { pbr = false; }
  23334. if (scale === void 0) { scale = 1000; }
  23335. if (blur === void 0) { blur = 0; }
  23336. if (environmentTexture) {
  23337. this.environmentTexture = environmentTexture;
  23338. }
  23339. if (!this.environmentTexture) {
  23340. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23341. return null;
  23342. }
  23343. // Skybox
  23344. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23345. if (pbr) {
  23346. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23347. hdrSkyboxMaterial.backFaceCulling = false;
  23348. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23349. if (hdrSkyboxMaterial.reflectionTexture) {
  23350. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23351. }
  23352. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23353. hdrSkyboxMaterial.disableLighting = true;
  23354. hdrSkyboxMaterial.twoSidedLighting = true;
  23355. hdrSkybox.infiniteDistance = true;
  23356. hdrSkybox.material = hdrSkyboxMaterial;
  23357. }
  23358. else {
  23359. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23360. skyboxMaterial.backFaceCulling = false;
  23361. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23362. if (skyboxMaterial.reflectionTexture) {
  23363. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23364. }
  23365. skyboxMaterial.disableLighting = true;
  23366. hdrSkybox.infiniteDistance = true;
  23367. hdrSkybox.material = skyboxMaterial;
  23368. }
  23369. return hdrSkybox;
  23370. };
  23371. Scene.prototype.createDefaultEnvironment = function (options) {
  23372. if (BABYLON.EnvironmentHelper) {
  23373. return new BABYLON.EnvironmentHelper(options, this);
  23374. }
  23375. return null;
  23376. };
  23377. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23378. if (webVROptions === void 0) { webVROptions = {}; }
  23379. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23380. };
  23381. // Tags
  23382. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23383. if (tagsQuery === undefined) {
  23384. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23385. return list;
  23386. }
  23387. var listByTags = [];
  23388. forEach = forEach || (function (item) { return; });
  23389. for (var i in list) {
  23390. var item = list[i];
  23391. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23392. listByTags.push(item);
  23393. forEach(item);
  23394. }
  23395. }
  23396. return listByTags;
  23397. };
  23398. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23399. return this._getByTags(this.meshes, tagsQuery, forEach);
  23400. };
  23401. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23402. return this._getByTags(this.cameras, tagsQuery, forEach);
  23403. };
  23404. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23405. return this._getByTags(this.lights, tagsQuery, forEach);
  23406. };
  23407. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23408. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23409. };
  23410. /**
  23411. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23412. * This allowed control for front to back rendering or reversly depending of the special needs.
  23413. *
  23414. * @param renderingGroupId The rendering group id corresponding to its index
  23415. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23416. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23417. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23418. */
  23419. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23420. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23421. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23422. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23423. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23424. };
  23425. /**
  23426. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23427. *
  23428. * @param renderingGroupId The rendering group id corresponding to its index
  23429. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23430. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23431. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23432. */
  23433. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23434. if (depth === void 0) { depth = true; }
  23435. if (stencil === void 0) { stencil = true; }
  23436. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23437. };
  23438. /**
  23439. * Will flag all materials as dirty to trigger new shader compilation
  23440. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23441. */
  23442. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23443. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23444. var material = _a[_i];
  23445. if (predicate && !predicate(material)) {
  23446. continue;
  23447. }
  23448. material.markAsDirty(flag);
  23449. }
  23450. };
  23451. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23452. var _this = this;
  23453. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23454. this._activeRequests.push(request);
  23455. request.onCompleteObservable.add(function (request) {
  23456. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23457. });
  23458. return request;
  23459. };
  23460. // Statics
  23461. Scene._FOGMODE_NONE = 0;
  23462. Scene._FOGMODE_EXP = 1;
  23463. Scene._FOGMODE_EXP2 = 2;
  23464. Scene._FOGMODE_LINEAR = 3;
  23465. Scene._uniqueIdCounter = 0;
  23466. Scene.MinDeltaTime = 1.0;
  23467. Scene.MaxDeltaTime = 1000.0;
  23468. /** The distance in pixel that you have to move to prevent some events */
  23469. Scene.DragMovementThreshold = 10; // in pixels
  23470. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23471. Scene.LongPressDelay = 500; // in milliseconds
  23472. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23473. Scene.DoubleClickDelay = 300; // in milliseconds
  23474. /** If you need to check double click without raising a single click at first click, enable this flag */
  23475. Scene.ExclusiveDoubleClickMode = false;
  23476. return Scene;
  23477. }());
  23478. BABYLON.Scene = Scene;
  23479. })(BABYLON || (BABYLON = {}));
  23480. //# sourceMappingURL=babylon.scene.js.map
  23481. var BABYLON;
  23482. (function (BABYLON) {
  23483. /**
  23484. * Set of assets to keep when moving a scene into an asset container.
  23485. */
  23486. var KeepAssets = /** @class */ (function () {
  23487. function KeepAssets() {
  23488. /**
  23489. * Cameras to keep.
  23490. */
  23491. this.cameras = new Array();
  23492. /**
  23493. * Lights to keep.
  23494. */
  23495. this.lights = new Array();
  23496. /**
  23497. * Meshes to keep.
  23498. */
  23499. this.meshes = new Array();
  23500. /**
  23501. * Skeletons to keep.
  23502. */
  23503. this.skeletons = new Array();
  23504. /**
  23505. * ParticleSystems to keep.
  23506. */
  23507. this.particleSystems = new Array();
  23508. /**
  23509. * Animations to keep.
  23510. */
  23511. this.animations = new Array();
  23512. /**
  23513. * MultiMaterials to keep.
  23514. */
  23515. this.multiMaterials = new Array();
  23516. /**
  23517. * Materials to keep.
  23518. */
  23519. this.materials = new Array();
  23520. /**
  23521. * MorphTargetManagers to keep.
  23522. */
  23523. this.morphTargetManagers = new Array();
  23524. /**
  23525. * Geometries to keep.
  23526. */
  23527. this.geometries = new Array();
  23528. /**
  23529. * TransformNodes to keep.
  23530. */
  23531. this.transformNodes = new Array();
  23532. /**
  23533. * LensFlareSystems to keep.
  23534. */
  23535. this.lensFlareSystems = new Array();
  23536. /**
  23537. * ShadowGenerators to keep.
  23538. */
  23539. this.shadowGenerators = new Array();
  23540. /**
  23541. * ActionManagers to keep.
  23542. */
  23543. this.actionManagers = new Array();
  23544. /**
  23545. * Sounds to keep.
  23546. */
  23547. this.sounds = new Array();
  23548. }
  23549. return KeepAssets;
  23550. }());
  23551. BABYLON.KeepAssets = KeepAssets;
  23552. /**
  23553. * Container with a set of assets that can be added or removed from a scene.
  23554. */
  23555. var AssetContainer = /** @class */ (function () {
  23556. /**
  23557. * Instantiates an AssetContainer.
  23558. * @param scene The scene the AssetContainer belongs to.
  23559. */
  23560. function AssetContainer(scene) {
  23561. // Objects
  23562. /**
  23563. * Cameras populated in the container.
  23564. */
  23565. this.cameras = new Array();
  23566. /**
  23567. * Lights populated in the container.
  23568. */
  23569. this.lights = new Array();
  23570. /**
  23571. * Meshes populated in the container.
  23572. */
  23573. this.meshes = new Array();
  23574. /**
  23575. * Skeletons populated in the container.
  23576. */
  23577. this.skeletons = new Array();
  23578. /**
  23579. * ParticleSystems populated in the container.
  23580. */
  23581. this.particleSystems = new Array();
  23582. /**
  23583. * Animations populated in the container.
  23584. */
  23585. this.animations = new Array();
  23586. /**
  23587. * MultiMaterials populated in the container.
  23588. */
  23589. this.multiMaterials = new Array();
  23590. /**
  23591. * Materials populated in the container.
  23592. */
  23593. this.materials = new Array();
  23594. /**
  23595. * MorphTargetManagers populated in the container.
  23596. */
  23597. this.morphTargetManagers = new Array();
  23598. /**
  23599. * Geometries populated in the container.
  23600. */
  23601. this.geometries = new Array();
  23602. /**
  23603. * TransformNodes populated in the container.
  23604. */
  23605. this.transformNodes = new Array();
  23606. /**
  23607. * LensFlareSystems populated in the container.
  23608. */
  23609. this.lensFlareSystems = new Array();
  23610. /**
  23611. * ShadowGenerators populated in the container.
  23612. */
  23613. this.shadowGenerators = new Array();
  23614. /**
  23615. * ActionManagers populated in the container.
  23616. */
  23617. this.actionManagers = new Array();
  23618. /**
  23619. * Sounds populated in the container.
  23620. */
  23621. this.sounds = new Array();
  23622. this.scene = scene;
  23623. }
  23624. /**
  23625. * Adds all the assets from the container to the scene.
  23626. */
  23627. AssetContainer.prototype.addAllToScene = function () {
  23628. var _this = this;
  23629. this.cameras.forEach(function (o) {
  23630. _this.scene.addCamera(o);
  23631. });
  23632. this.lights.forEach(function (o) {
  23633. _this.scene.addLight(o);
  23634. });
  23635. this.meshes.forEach(function (o) {
  23636. _this.scene.addMesh(o);
  23637. });
  23638. this.skeletons.forEach(function (o) {
  23639. _this.scene.addSkeleton(o);
  23640. });
  23641. this.particleSystems.forEach(function (o) {
  23642. _this.scene.addParticleSystem(o);
  23643. });
  23644. this.animations.forEach(function (o) {
  23645. _this.scene.addAnimation(o);
  23646. });
  23647. this.multiMaterials.forEach(function (o) {
  23648. _this.scene.addMultiMaterial(o);
  23649. });
  23650. this.materials.forEach(function (o) {
  23651. _this.scene.addMaterial(o);
  23652. });
  23653. this.morphTargetManagers.forEach(function (o) {
  23654. _this.scene.addMorphTargetManager(o);
  23655. });
  23656. this.geometries.forEach(function (o) {
  23657. _this.scene.addGeometry(o);
  23658. });
  23659. this.transformNodes.forEach(function (o) {
  23660. _this.scene.addTransformNode(o);
  23661. });
  23662. this.lensFlareSystems.forEach(function (o) {
  23663. _this.scene.addLensFlareSystem(o);
  23664. });
  23665. this.actionManagers.forEach(function (o) {
  23666. _this.scene.addActionManager(o);
  23667. });
  23668. this.sounds.forEach(function (o) {
  23669. o.play();
  23670. o.autoplay = true;
  23671. _this.scene.mainSoundTrack.AddSound(o);
  23672. });
  23673. };
  23674. /**
  23675. * Removes all the assets in the container from the scene
  23676. */
  23677. AssetContainer.prototype.removeAllFromScene = function () {
  23678. var _this = this;
  23679. this.cameras.forEach(function (o) {
  23680. _this.scene.removeCamera(o);
  23681. });
  23682. this.lights.forEach(function (o) {
  23683. _this.scene.removeLight(o);
  23684. });
  23685. this.meshes.forEach(function (o) {
  23686. _this.scene.removeMesh(o);
  23687. });
  23688. this.skeletons.forEach(function (o) {
  23689. _this.scene.removeSkeleton(o);
  23690. });
  23691. this.particleSystems.forEach(function (o) {
  23692. _this.scene.removeParticleSystem(o);
  23693. });
  23694. this.animations.forEach(function (o) {
  23695. _this.scene.removeAnimation(o);
  23696. });
  23697. this.multiMaterials.forEach(function (o) {
  23698. _this.scene.removeMultiMaterial(o);
  23699. });
  23700. this.materials.forEach(function (o) {
  23701. _this.scene.removeMaterial(o);
  23702. });
  23703. this.morphTargetManagers.forEach(function (o) {
  23704. _this.scene.removeMorphTargetManager(o);
  23705. });
  23706. this.geometries.forEach(function (o) {
  23707. _this.scene.removeGeometry(o);
  23708. });
  23709. this.transformNodes.forEach(function (o) {
  23710. _this.scene.removeTransformNode(o);
  23711. });
  23712. this.lensFlareSystems.forEach(function (o) {
  23713. _this.scene.removeLensFlareSystem(o);
  23714. });
  23715. this.actionManagers.forEach(function (o) {
  23716. _this.scene.removeActionManager(o);
  23717. });
  23718. this.sounds.forEach(function (o) {
  23719. o.stop();
  23720. o.autoplay = false;
  23721. _this.scene.mainSoundTrack.RemoveSound(o);
  23722. });
  23723. };
  23724. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  23725. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  23726. var asset = sourceAssets_1[_i];
  23727. var move = true;
  23728. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  23729. var keepAsset = keepAssets_1[_a];
  23730. if (asset === keepAsset) {
  23731. move = false;
  23732. break;
  23733. }
  23734. }
  23735. if (move) {
  23736. targetAssets.push(asset);
  23737. }
  23738. }
  23739. };
  23740. /**
  23741. * Removes all the assets contained in the scene and adds them to the container.
  23742. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  23743. */
  23744. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  23745. if (keepAssets === undefined) {
  23746. keepAssets = new KeepAssets();
  23747. }
  23748. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  23749. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  23750. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  23751. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  23752. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  23753. Array.prototype.push.apply(this.animations, this.scene.animations);
  23754. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  23755. Array.prototype.push.apply(this.lights, this.scene.lights);
  23756. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  23757. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  23758. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  23759. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  23760. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  23761. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  23762. this.removeAllFromScene();
  23763. };
  23764. return AssetContainer;
  23765. }());
  23766. BABYLON.AssetContainer = AssetContainer;
  23767. })(BABYLON || (BABYLON = {}));
  23768. //# sourceMappingURL=babylon.assetContainer.js.map
  23769. var BABYLON;
  23770. (function (BABYLON) {
  23771. var Buffer = /** @class */ (function () {
  23772. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23773. if (instanced === void 0) { instanced = false; }
  23774. if (engine instanceof BABYLON.Mesh) {
  23775. this._engine = engine.getScene().getEngine();
  23776. }
  23777. else {
  23778. this._engine = engine;
  23779. }
  23780. this._updatable = updatable;
  23781. this._data = data;
  23782. this._strideSize = stride;
  23783. if (!postponeInternalCreation) {
  23784. this.create();
  23785. }
  23786. this._instanced = instanced;
  23787. this._instanceDivisor = instanced ? 1 : 0;
  23788. }
  23789. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23790. // a lot of these parameters are ignored as they are overriden by the buffer
  23791. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23792. };
  23793. // Properties
  23794. Buffer.prototype.isUpdatable = function () {
  23795. return this._updatable;
  23796. };
  23797. Buffer.prototype.getData = function () {
  23798. return this._data;
  23799. };
  23800. Buffer.prototype.getBuffer = function () {
  23801. return this._buffer;
  23802. };
  23803. Buffer.prototype.getStrideSize = function () {
  23804. return this._strideSize;
  23805. };
  23806. Buffer.prototype.getIsInstanced = function () {
  23807. return this._instanced;
  23808. };
  23809. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23810. get: function () {
  23811. return this._instanceDivisor;
  23812. },
  23813. set: function (value) {
  23814. this._instanceDivisor = value;
  23815. if (value == 0) {
  23816. this._instanced = false;
  23817. }
  23818. else {
  23819. this._instanced = true;
  23820. }
  23821. },
  23822. enumerable: true,
  23823. configurable: true
  23824. });
  23825. // Methods
  23826. Buffer.prototype.create = function (data) {
  23827. if (data === void 0) { data = null; }
  23828. if (!data && this._buffer) {
  23829. return; // nothing to do
  23830. }
  23831. data = data || this._data;
  23832. if (!data) {
  23833. return;
  23834. }
  23835. if (!this._buffer) {
  23836. if (this._updatable) {
  23837. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23838. this._data = data;
  23839. }
  23840. else {
  23841. this._buffer = this._engine.createVertexBuffer(data);
  23842. }
  23843. }
  23844. else if (this._updatable) {
  23845. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23846. this._data = data;
  23847. }
  23848. };
  23849. Buffer.prototype._rebuild = function () {
  23850. this._buffer = null;
  23851. this.create(this._data);
  23852. };
  23853. Buffer.prototype.update = function (data) {
  23854. this.create(data);
  23855. };
  23856. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23857. if (!this._buffer) {
  23858. return;
  23859. }
  23860. if (this._updatable) {
  23861. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23862. this._data = null;
  23863. }
  23864. };
  23865. Buffer.prototype.dispose = function () {
  23866. if (!this._buffer) {
  23867. return;
  23868. }
  23869. if (this._engine._releaseBuffer(this._buffer)) {
  23870. this._buffer = null;
  23871. }
  23872. };
  23873. return Buffer;
  23874. }());
  23875. BABYLON.Buffer = Buffer;
  23876. })(BABYLON || (BABYLON = {}));
  23877. //# sourceMappingURL=babylon.buffer.js.map
  23878. var BABYLON;
  23879. (function (BABYLON) {
  23880. var VertexBuffer = /** @class */ (function () {
  23881. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23882. if (!stride) {
  23883. // Deduce stride from kind
  23884. switch (kind) {
  23885. case VertexBuffer.PositionKind:
  23886. stride = 3;
  23887. break;
  23888. case VertexBuffer.NormalKind:
  23889. stride = 3;
  23890. break;
  23891. case VertexBuffer.UVKind:
  23892. case VertexBuffer.UV2Kind:
  23893. case VertexBuffer.UV3Kind:
  23894. case VertexBuffer.UV4Kind:
  23895. case VertexBuffer.UV5Kind:
  23896. case VertexBuffer.UV6Kind:
  23897. stride = 2;
  23898. break;
  23899. case VertexBuffer.TangentKind:
  23900. case VertexBuffer.ColorKind:
  23901. stride = 4;
  23902. break;
  23903. case VertexBuffer.MatricesIndicesKind:
  23904. case VertexBuffer.MatricesIndicesExtraKind:
  23905. stride = 4;
  23906. break;
  23907. case VertexBuffer.MatricesWeightsKind:
  23908. case VertexBuffer.MatricesWeightsExtraKind:
  23909. default:
  23910. stride = 4;
  23911. break;
  23912. }
  23913. }
  23914. if (data instanceof BABYLON.Buffer) {
  23915. if (!stride) {
  23916. stride = data.getStrideSize();
  23917. }
  23918. this._buffer = data;
  23919. this._ownsBuffer = false;
  23920. }
  23921. else {
  23922. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23923. this._ownsBuffer = true;
  23924. }
  23925. this._stride = stride;
  23926. this._offset = offset ? offset : 0;
  23927. this._size = size ? size : stride;
  23928. this._kind = kind;
  23929. }
  23930. VertexBuffer.prototype._rebuild = function () {
  23931. if (!this._buffer) {
  23932. return;
  23933. }
  23934. this._buffer._rebuild();
  23935. };
  23936. /**
  23937. * Returns the kind of the VertexBuffer (string).
  23938. */
  23939. VertexBuffer.prototype.getKind = function () {
  23940. return this._kind;
  23941. };
  23942. // Properties
  23943. /**
  23944. * Boolean : is the VertexBuffer updatable ?
  23945. */
  23946. VertexBuffer.prototype.isUpdatable = function () {
  23947. return this._buffer.isUpdatable();
  23948. };
  23949. /**
  23950. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23951. */
  23952. VertexBuffer.prototype.getData = function () {
  23953. return this._buffer.getData();
  23954. };
  23955. /**
  23956. * Returns the WebGLBuffer associated to the VertexBuffer.
  23957. */
  23958. VertexBuffer.prototype.getBuffer = function () {
  23959. return this._buffer.getBuffer();
  23960. };
  23961. /**
  23962. * Returns the stride of the VertexBuffer (integer).
  23963. */
  23964. VertexBuffer.prototype.getStrideSize = function () {
  23965. return this._stride;
  23966. };
  23967. /**
  23968. * Returns the offset (integer).
  23969. */
  23970. VertexBuffer.prototype.getOffset = function () {
  23971. return this._offset;
  23972. };
  23973. /**
  23974. * Returns the VertexBuffer total size (integer).
  23975. */
  23976. VertexBuffer.prototype.getSize = function () {
  23977. return this._size;
  23978. };
  23979. /**
  23980. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23981. */
  23982. VertexBuffer.prototype.getIsInstanced = function () {
  23983. return this._buffer.getIsInstanced();
  23984. };
  23985. /**
  23986. * Returns the instancing divisor, zero for non-instanced (integer).
  23987. */
  23988. VertexBuffer.prototype.getInstanceDivisor = function () {
  23989. return this._buffer.instanceDivisor;
  23990. };
  23991. // Methods
  23992. /**
  23993. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23994. * Returns the created WebGLBuffer.
  23995. */
  23996. VertexBuffer.prototype.create = function (data) {
  23997. return this._buffer.create(data);
  23998. };
  23999. /**
  24000. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24001. * This function will create a new buffer if the current one is not updatable
  24002. * Returns the updated WebGLBuffer.
  24003. */
  24004. VertexBuffer.prototype.update = function (data) {
  24005. return this._buffer.update(data);
  24006. };
  24007. /**
  24008. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24009. * Returns the directly updated WebGLBuffer.
  24010. */
  24011. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24012. return this._buffer.updateDirectly(data, offset);
  24013. };
  24014. /**
  24015. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24016. */
  24017. VertexBuffer.prototype.dispose = function () {
  24018. if (this._ownsBuffer) {
  24019. this._buffer.dispose();
  24020. }
  24021. };
  24022. Object.defineProperty(VertexBuffer, "PositionKind", {
  24023. get: function () {
  24024. return VertexBuffer._PositionKind;
  24025. },
  24026. enumerable: true,
  24027. configurable: true
  24028. });
  24029. Object.defineProperty(VertexBuffer, "NormalKind", {
  24030. get: function () {
  24031. return VertexBuffer._NormalKind;
  24032. },
  24033. enumerable: true,
  24034. configurable: true
  24035. });
  24036. Object.defineProperty(VertexBuffer, "TangentKind", {
  24037. get: function () {
  24038. return VertexBuffer._TangentKind;
  24039. },
  24040. enumerable: true,
  24041. configurable: true
  24042. });
  24043. Object.defineProperty(VertexBuffer, "UVKind", {
  24044. get: function () {
  24045. return VertexBuffer._UVKind;
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24051. get: function () {
  24052. return VertexBuffer._UV2Kind;
  24053. },
  24054. enumerable: true,
  24055. configurable: true
  24056. });
  24057. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24058. get: function () {
  24059. return VertexBuffer._UV3Kind;
  24060. },
  24061. enumerable: true,
  24062. configurable: true
  24063. });
  24064. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24065. get: function () {
  24066. return VertexBuffer._UV4Kind;
  24067. },
  24068. enumerable: true,
  24069. configurable: true
  24070. });
  24071. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24072. get: function () {
  24073. return VertexBuffer._UV5Kind;
  24074. },
  24075. enumerable: true,
  24076. configurable: true
  24077. });
  24078. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24079. get: function () {
  24080. return VertexBuffer._UV6Kind;
  24081. },
  24082. enumerable: true,
  24083. configurable: true
  24084. });
  24085. Object.defineProperty(VertexBuffer, "ColorKind", {
  24086. get: function () {
  24087. return VertexBuffer._ColorKind;
  24088. },
  24089. enumerable: true,
  24090. configurable: true
  24091. });
  24092. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24093. get: function () {
  24094. return VertexBuffer._MatricesIndicesKind;
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24100. get: function () {
  24101. return VertexBuffer._MatricesWeightsKind;
  24102. },
  24103. enumerable: true,
  24104. configurable: true
  24105. });
  24106. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24107. get: function () {
  24108. return VertexBuffer._MatricesIndicesExtraKind;
  24109. },
  24110. enumerable: true,
  24111. configurable: true
  24112. });
  24113. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24114. get: function () {
  24115. return VertexBuffer._MatricesWeightsExtraKind;
  24116. },
  24117. enumerable: true,
  24118. configurable: true
  24119. });
  24120. // Enums
  24121. VertexBuffer._PositionKind = "position";
  24122. VertexBuffer._NormalKind = "normal";
  24123. VertexBuffer._TangentKind = "tangent";
  24124. VertexBuffer._UVKind = "uv";
  24125. VertexBuffer._UV2Kind = "uv2";
  24126. VertexBuffer._UV3Kind = "uv3";
  24127. VertexBuffer._UV4Kind = "uv4";
  24128. VertexBuffer._UV5Kind = "uv5";
  24129. VertexBuffer._UV6Kind = "uv6";
  24130. VertexBuffer._ColorKind = "color";
  24131. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24132. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24133. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24134. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24135. return VertexBuffer;
  24136. }());
  24137. BABYLON.VertexBuffer = VertexBuffer;
  24138. })(BABYLON || (BABYLON = {}));
  24139. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24140. var BABYLON;
  24141. (function (BABYLON) {
  24142. /**
  24143. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24144. */
  24145. var DummyInternalTextureTracker = /** @class */ (function () {
  24146. function DummyInternalTextureTracker() {
  24147. /**
  24148. * Gets or set the previous tracker in the list
  24149. */
  24150. this.previous = null;
  24151. /**
  24152. * Gets or set the next tracker in the list
  24153. */
  24154. this.next = null;
  24155. }
  24156. return DummyInternalTextureTracker;
  24157. }());
  24158. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24159. })(BABYLON || (BABYLON = {}));
  24160. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24161. var BABYLON;
  24162. (function (BABYLON) {
  24163. /**
  24164. * Class used to store data associated with WebGL texture data for the engine
  24165. * This class should not be used directly
  24166. */
  24167. var InternalTexture = /** @class */ (function () {
  24168. /**
  24169. * Creates a new InternalTexture
  24170. * @param engine defines the engine to use
  24171. * @param dataSource defines the type of data that will be used
  24172. */
  24173. function InternalTexture(engine, dataSource) {
  24174. /**
  24175. * Observable called when the texture is loaded
  24176. */
  24177. this.onLoadedObservable = new BABYLON.Observable();
  24178. /**
  24179. * Gets or set the previous tracker in the list
  24180. */
  24181. this.previous = null;
  24182. /**
  24183. * Gets or set the next tracker in the list
  24184. */
  24185. this.next = null;
  24186. // Private
  24187. /** @ignore */
  24188. this._initialSlot = -1;
  24189. /** @ignore */
  24190. this._designatedSlot = -1;
  24191. /** @ignore */
  24192. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24193. /** @ignore */
  24194. this._references = 1;
  24195. this._engine = engine;
  24196. this._dataSource = dataSource;
  24197. this._webGLTexture = engine._createTexture();
  24198. }
  24199. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24200. /**
  24201. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24202. */
  24203. get: function () {
  24204. return this._dataSource;
  24205. },
  24206. enumerable: true,
  24207. configurable: true
  24208. });
  24209. /**
  24210. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24211. */
  24212. InternalTexture.prototype.incrementReferences = function () {
  24213. this._references++;
  24214. };
  24215. /**
  24216. * Change the size of the texture (not the size of the content)
  24217. * @param width defines the new width
  24218. * @param height defines the new height
  24219. * @param depth defines the new depth (1 by default)
  24220. */
  24221. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24222. if (depth === void 0) { depth = 1; }
  24223. this.width = width;
  24224. this.height = height;
  24225. this.depth = depth;
  24226. this.baseWidth = width;
  24227. this.baseHeight = height;
  24228. this.baseDepth = depth;
  24229. this._size = width * height * depth;
  24230. };
  24231. /** @ignore */
  24232. InternalTexture.prototype._rebuild = function () {
  24233. var _this = this;
  24234. var proxy;
  24235. this.isReady = false;
  24236. this._cachedCoordinatesMode = null;
  24237. this._cachedWrapU = null;
  24238. this._cachedWrapV = null;
  24239. this._cachedAnisotropicFilteringLevel = null;
  24240. switch (this._dataSource) {
  24241. case InternalTexture.DATASOURCE_TEMP:
  24242. return;
  24243. case InternalTexture.DATASOURCE_URL:
  24244. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24245. _this.isReady = true;
  24246. }, null, this._buffer, undefined, this.format);
  24247. proxy._swapAndDie(this);
  24248. return;
  24249. case InternalTexture.DATASOURCE_RAW:
  24250. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24251. proxy._swapAndDie(this);
  24252. this.isReady = true;
  24253. return;
  24254. case InternalTexture.DATASOURCE_RAW3D:
  24255. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24256. proxy._swapAndDie(this);
  24257. this.isReady = true;
  24258. return;
  24259. case InternalTexture.DATASOURCE_DYNAMIC:
  24260. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24261. proxy._swapAndDie(this);
  24262. // The engine will make sure to update content so no need to flag it as isReady = true
  24263. return;
  24264. case InternalTexture.DATASOURCE_RENDERTARGET:
  24265. var options = new BABYLON.RenderTargetCreationOptions();
  24266. options.generateDepthBuffer = this._generateDepthBuffer;
  24267. options.generateMipMaps = this.generateMipMaps;
  24268. options.generateStencilBuffer = this._generateStencilBuffer;
  24269. options.samplingMode = this.samplingMode;
  24270. options.type = this.type;
  24271. if (this.isCube) {
  24272. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24273. }
  24274. else {
  24275. var size = {
  24276. width: this.width,
  24277. height: this.height
  24278. };
  24279. proxy = this._engine.createRenderTargetTexture(size, options);
  24280. }
  24281. proxy._swapAndDie(this);
  24282. this.isReady = true;
  24283. return;
  24284. case InternalTexture.DATASOURCE_CUBE:
  24285. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24286. _this.isReady = true;
  24287. }, null, this.format, this._extension);
  24288. proxy._swapAndDie(this);
  24289. return;
  24290. case InternalTexture.DATASOURCE_CUBERAW:
  24291. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24292. proxy._swapAndDie(this);
  24293. this.isReady = true;
  24294. return;
  24295. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24296. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24297. if (proxy) {
  24298. proxy._swapAndDie(_this);
  24299. }
  24300. _this.isReady = true;
  24301. }, null, this.format, this._extension);
  24302. return;
  24303. }
  24304. };
  24305. InternalTexture.prototype._swapAndDie = function (target) {
  24306. target._webGLTexture = this._webGLTexture;
  24307. if (this._framebuffer) {
  24308. target._framebuffer = this._framebuffer;
  24309. }
  24310. if (this._depthStencilBuffer) {
  24311. target._depthStencilBuffer = this._depthStencilBuffer;
  24312. }
  24313. if (this._lodTextureHigh) {
  24314. if (target._lodTextureHigh) {
  24315. target._lodTextureHigh.dispose();
  24316. }
  24317. target._lodTextureHigh = this._lodTextureHigh;
  24318. }
  24319. if (this._lodTextureMid) {
  24320. if (target._lodTextureMid) {
  24321. target._lodTextureMid.dispose();
  24322. }
  24323. target._lodTextureMid = this._lodTextureMid;
  24324. }
  24325. if (this._lodTextureLow) {
  24326. if (target._lodTextureLow) {
  24327. target._lodTextureLow.dispose();
  24328. }
  24329. target._lodTextureLow = this._lodTextureLow;
  24330. }
  24331. var cache = this._engine.getLoadedTexturesCache();
  24332. var index = cache.indexOf(this);
  24333. if (index !== -1) {
  24334. cache.splice(index, 1);
  24335. }
  24336. };
  24337. /**
  24338. * Dispose the current allocated resources
  24339. */
  24340. InternalTexture.prototype.dispose = function () {
  24341. if (!this._webGLTexture) {
  24342. return;
  24343. }
  24344. this._references--;
  24345. if (this._references === 0) {
  24346. this._engine._releaseTexture(this);
  24347. this._webGLTexture = null;
  24348. this.previous = null;
  24349. this.next = null;
  24350. }
  24351. };
  24352. /**
  24353. * The source of the texture data is unknown
  24354. */
  24355. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24356. /**
  24357. * Texture data comes from an URL
  24358. */
  24359. InternalTexture.DATASOURCE_URL = 1;
  24360. /**
  24361. * Texture data is only used for temporary storage
  24362. */
  24363. InternalTexture.DATASOURCE_TEMP = 2;
  24364. /**
  24365. * Texture data comes from raw data (ArrayBuffer)
  24366. */
  24367. InternalTexture.DATASOURCE_RAW = 3;
  24368. /**
  24369. * Texture content is dynamic (video or dynamic texture)
  24370. */
  24371. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24372. /**
  24373. * Texture content is generated by rendering to it
  24374. */
  24375. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24376. /**
  24377. * Texture content is part of a multi render target process
  24378. */
  24379. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24380. /**
  24381. * Texture data comes from a cube data file
  24382. */
  24383. InternalTexture.DATASOURCE_CUBE = 7;
  24384. /**
  24385. * Texture data comes from a raw cube data
  24386. */
  24387. InternalTexture.DATASOURCE_CUBERAW = 8;
  24388. /**
  24389. * Texture data come from a prefiltered cube data file
  24390. */
  24391. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24392. /**
  24393. * Texture content is raw 3D data
  24394. */
  24395. InternalTexture.DATASOURCE_RAW3D = 10;
  24396. return InternalTexture;
  24397. }());
  24398. BABYLON.InternalTexture = InternalTexture;
  24399. })(BABYLON || (BABYLON = {}));
  24400. //# sourceMappingURL=babylon.internalTexture.js.map
  24401. var BABYLON;
  24402. (function (BABYLON) {
  24403. var BaseTexture = /** @class */ (function () {
  24404. function BaseTexture(scene) {
  24405. this._hasAlpha = false;
  24406. this.getAlphaFromRGB = false;
  24407. this.level = 1;
  24408. this.coordinatesIndex = 0;
  24409. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24410. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24411. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24412. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24413. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24414. this.isCube = false;
  24415. this.is3D = false;
  24416. this.gammaSpace = true;
  24417. this.invertZ = false;
  24418. this.lodLevelInAlpha = false;
  24419. this.lodGenerationOffset = 0.0;
  24420. this.lodGenerationScale = 0.8;
  24421. this.isRenderTarget = false;
  24422. this.animations = new Array();
  24423. /**
  24424. * An event triggered when the texture is disposed.
  24425. * @type {BABYLON.Observable}
  24426. */
  24427. this.onDisposeObservable = new BABYLON.Observable();
  24428. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24429. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24430. if (this._scene) {
  24431. this._scene.textures.push(this);
  24432. }
  24433. this._uid = null;
  24434. }
  24435. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24436. get: function () {
  24437. return this._hasAlpha;
  24438. },
  24439. set: function (value) {
  24440. if (this._hasAlpha === value) {
  24441. return;
  24442. }
  24443. this._hasAlpha = value;
  24444. if (this._scene) {
  24445. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24446. }
  24447. },
  24448. enumerable: true,
  24449. configurable: true
  24450. });
  24451. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24452. get: function () {
  24453. return this._coordinatesMode;
  24454. },
  24455. set: function (value) {
  24456. if (this._coordinatesMode === value) {
  24457. return;
  24458. }
  24459. this._coordinatesMode = value;
  24460. if (this._scene) {
  24461. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24462. }
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(BaseTexture.prototype, "uid", {
  24468. get: function () {
  24469. if (!this._uid) {
  24470. this._uid = BABYLON.Tools.RandomId();
  24471. }
  24472. return this._uid;
  24473. },
  24474. enumerable: true,
  24475. configurable: true
  24476. });
  24477. BaseTexture.prototype.toString = function () {
  24478. return this.name;
  24479. };
  24480. BaseTexture.prototype.getClassName = function () {
  24481. return "BaseTexture";
  24482. };
  24483. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24484. set: function (callback) {
  24485. if (this._onDisposeObserver) {
  24486. this.onDisposeObservable.remove(this._onDisposeObserver);
  24487. }
  24488. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24489. },
  24490. enumerable: true,
  24491. configurable: true
  24492. });
  24493. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24494. get: function () {
  24495. return true;
  24496. },
  24497. enumerable: true,
  24498. configurable: true
  24499. });
  24500. BaseTexture.prototype.getScene = function () {
  24501. return this._scene;
  24502. };
  24503. BaseTexture.prototype.getTextureMatrix = function () {
  24504. return BABYLON.Matrix.IdentityReadOnly;
  24505. };
  24506. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24507. return BABYLON.Matrix.IdentityReadOnly;
  24508. };
  24509. BaseTexture.prototype.getInternalTexture = function () {
  24510. return this._texture;
  24511. };
  24512. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24513. return !this.isBlocking || this.isReady();
  24514. };
  24515. BaseTexture.prototype.isReady = function () {
  24516. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24517. this.delayLoad();
  24518. return false;
  24519. }
  24520. if (this._texture) {
  24521. return this._texture.isReady;
  24522. }
  24523. return false;
  24524. };
  24525. BaseTexture.prototype.getSize = function () {
  24526. if (this._texture && this._texture.width) {
  24527. return new BABYLON.Size(this._texture.width, this._texture.height);
  24528. }
  24529. if (this._texture && this._texture._size) {
  24530. return new BABYLON.Size(this._texture._size, this._texture._size);
  24531. }
  24532. return BABYLON.Size.Zero();
  24533. };
  24534. BaseTexture.prototype.getBaseSize = function () {
  24535. if (!this.isReady() || !this._texture)
  24536. return BABYLON.Size.Zero();
  24537. if (this._texture._size) {
  24538. return new BABYLON.Size(this._texture._size, this._texture._size);
  24539. }
  24540. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24541. };
  24542. BaseTexture.prototype.scale = function (ratio) {
  24543. };
  24544. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24545. get: function () {
  24546. return false;
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24552. if (!this._scene) {
  24553. return null;
  24554. }
  24555. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24556. for (var index = 0; index < texturesCache.length; index++) {
  24557. var texturesCacheEntry = texturesCache[index];
  24558. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24559. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24560. texturesCacheEntry.incrementReferences();
  24561. return texturesCacheEntry;
  24562. }
  24563. }
  24564. }
  24565. return null;
  24566. };
  24567. BaseTexture.prototype._rebuild = function () {
  24568. };
  24569. BaseTexture.prototype.delayLoad = function () {
  24570. };
  24571. BaseTexture.prototype.clone = function () {
  24572. return null;
  24573. };
  24574. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24575. get: function () {
  24576. if (!this._texture) {
  24577. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24578. }
  24579. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24580. },
  24581. enumerable: true,
  24582. configurable: true
  24583. });
  24584. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24585. get: function () {
  24586. if (!this._texture) {
  24587. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24588. }
  24589. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. BaseTexture.prototype.readPixels = function (faceIndex) {
  24595. if (faceIndex === void 0) { faceIndex = 0; }
  24596. if (!this._texture) {
  24597. return null;
  24598. }
  24599. var size = this.getSize();
  24600. var scene = this.getScene();
  24601. if (!scene) {
  24602. return null;
  24603. }
  24604. var engine = scene.getEngine();
  24605. if (this._texture.isCube) {
  24606. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24607. }
  24608. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24609. };
  24610. BaseTexture.prototype.releaseInternalTexture = function () {
  24611. if (this._texture) {
  24612. this._texture.dispose();
  24613. this._texture = null;
  24614. }
  24615. };
  24616. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24617. get: function () {
  24618. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24619. return null;
  24620. }
  24621. if (!this._texture._sphericalPolynomial) {
  24622. this._texture._sphericalPolynomial =
  24623. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24624. }
  24625. return this._texture._sphericalPolynomial;
  24626. },
  24627. set: function (value) {
  24628. if (this._texture) {
  24629. this._texture._sphericalPolynomial = value;
  24630. }
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24636. get: function () {
  24637. if (this._texture) {
  24638. return this._texture._lodTextureHigh;
  24639. }
  24640. return null;
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24646. get: function () {
  24647. if (this._texture) {
  24648. return this._texture._lodTextureMid;
  24649. }
  24650. return null;
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24656. get: function () {
  24657. if (this._texture) {
  24658. return this._texture._lodTextureLow;
  24659. }
  24660. return null;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. BaseTexture.prototype.dispose = function () {
  24666. if (!this._scene) {
  24667. return;
  24668. }
  24669. // Animations
  24670. this._scene.stopAnimation(this);
  24671. // Remove from scene
  24672. this._scene._removePendingData(this);
  24673. var index = this._scene.textures.indexOf(this);
  24674. if (index >= 0) {
  24675. this._scene.textures.splice(index, 1);
  24676. }
  24677. if (this._texture === undefined) {
  24678. return;
  24679. }
  24680. // Release
  24681. this.releaseInternalTexture();
  24682. // Callback
  24683. this.onDisposeObservable.notifyObservers(this);
  24684. this.onDisposeObservable.clear();
  24685. };
  24686. BaseTexture.prototype.serialize = function () {
  24687. if (!this.name) {
  24688. return null;
  24689. }
  24690. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24691. // Animations
  24692. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24693. return serializationObject;
  24694. };
  24695. BaseTexture.WhenAllReady = function (textures, callback) {
  24696. var numRemaining = textures.length;
  24697. if (numRemaining === 0) {
  24698. callback();
  24699. return;
  24700. }
  24701. var _loop_1 = function () {
  24702. texture = textures[i];
  24703. if (texture.isReady()) {
  24704. if (--numRemaining === 0) {
  24705. callback();
  24706. }
  24707. }
  24708. else {
  24709. onLoadObservable = texture.onLoadObservable;
  24710. var onLoadCallback_1 = function () {
  24711. onLoadObservable.removeCallback(onLoadCallback_1);
  24712. if (--numRemaining === 0) {
  24713. callback();
  24714. }
  24715. };
  24716. onLoadObservable.add(onLoadCallback_1);
  24717. }
  24718. };
  24719. var texture, onLoadObservable;
  24720. for (var i = 0; i < textures.length; i++) {
  24721. _loop_1();
  24722. }
  24723. };
  24724. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24725. __decorate([
  24726. BABYLON.serialize()
  24727. ], BaseTexture.prototype, "name", void 0);
  24728. __decorate([
  24729. BABYLON.serialize("hasAlpha")
  24730. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24731. __decorate([
  24732. BABYLON.serialize()
  24733. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24734. __decorate([
  24735. BABYLON.serialize()
  24736. ], BaseTexture.prototype, "level", void 0);
  24737. __decorate([
  24738. BABYLON.serialize()
  24739. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24740. __decorate([
  24741. BABYLON.serialize("coordinatesMode")
  24742. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24743. __decorate([
  24744. BABYLON.serialize()
  24745. ], BaseTexture.prototype, "wrapU", void 0);
  24746. __decorate([
  24747. BABYLON.serialize()
  24748. ], BaseTexture.prototype, "wrapV", void 0);
  24749. __decorate([
  24750. BABYLON.serialize()
  24751. ], BaseTexture.prototype, "wrapR", void 0);
  24752. __decorate([
  24753. BABYLON.serialize()
  24754. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24755. __decorate([
  24756. BABYLON.serialize()
  24757. ], BaseTexture.prototype, "isCube", void 0);
  24758. __decorate([
  24759. BABYLON.serialize()
  24760. ], BaseTexture.prototype, "is3D", void 0);
  24761. __decorate([
  24762. BABYLON.serialize()
  24763. ], BaseTexture.prototype, "gammaSpace", void 0);
  24764. __decorate([
  24765. BABYLON.serialize()
  24766. ], BaseTexture.prototype, "invertZ", void 0);
  24767. __decorate([
  24768. BABYLON.serialize()
  24769. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24770. __decorate([
  24771. BABYLON.serialize()
  24772. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24773. __decorate([
  24774. BABYLON.serialize()
  24775. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24776. __decorate([
  24777. BABYLON.serialize()
  24778. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24779. return BaseTexture;
  24780. }());
  24781. BABYLON.BaseTexture = BaseTexture;
  24782. })(BABYLON || (BABYLON = {}));
  24783. //# sourceMappingURL=babylon.baseTexture.js.map
  24784. var BABYLON;
  24785. (function (BABYLON) {
  24786. var Texture = /** @class */ (function (_super) {
  24787. __extends(Texture, _super);
  24788. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24789. if (noMipmap === void 0) { noMipmap = false; }
  24790. if (invertY === void 0) { invertY = true; }
  24791. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24792. if (onLoad === void 0) { onLoad = null; }
  24793. if (onError === void 0) { onError = null; }
  24794. if (buffer === void 0) { buffer = null; }
  24795. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24796. var _this = _super.call(this, scene) || this;
  24797. _this.uOffset = 0;
  24798. _this.vOffset = 0;
  24799. _this.uScale = 1.0;
  24800. _this.vScale = 1.0;
  24801. _this.uAng = 0;
  24802. _this.vAng = 0;
  24803. _this.wAng = 0;
  24804. _this._isBlocking = true;
  24805. _this.name = url || "";
  24806. _this.url = url;
  24807. _this._noMipmap = noMipmap;
  24808. _this._invertY = invertY;
  24809. _this._samplingMode = samplingMode;
  24810. _this._buffer = buffer;
  24811. _this._deleteBuffer = deleteBuffer;
  24812. if (format) {
  24813. _this._format = format;
  24814. }
  24815. scene = _this.getScene();
  24816. if (!scene) {
  24817. return _this;
  24818. }
  24819. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24820. var load = function () {
  24821. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24822. _this.onLoadObservable.notifyObservers(_this);
  24823. }
  24824. if (onLoad) {
  24825. onLoad();
  24826. }
  24827. if (!_this.isBlocking && scene) {
  24828. scene.resetCachedMaterial();
  24829. }
  24830. };
  24831. if (!_this.url) {
  24832. _this._delayedOnLoad = load;
  24833. _this._delayedOnError = onError;
  24834. return _this;
  24835. }
  24836. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24837. if (!_this._texture) {
  24838. if (!scene.useDelayedTextureLoading) {
  24839. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24840. if (deleteBuffer) {
  24841. delete _this._buffer;
  24842. }
  24843. }
  24844. else {
  24845. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24846. _this._delayedOnLoad = load;
  24847. _this._delayedOnError = onError;
  24848. }
  24849. }
  24850. else {
  24851. if (_this._texture.isReady) {
  24852. BABYLON.Tools.SetImmediate(function () { return load(); });
  24853. }
  24854. else {
  24855. _this._texture.onLoadedObservable.add(load);
  24856. }
  24857. }
  24858. return _this;
  24859. }
  24860. Object.defineProperty(Texture.prototype, "noMipmap", {
  24861. get: function () {
  24862. return this._noMipmap;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. Object.defineProperty(Texture.prototype, "isBlocking", {
  24868. get: function () {
  24869. return this._isBlocking;
  24870. },
  24871. set: function (value) {
  24872. this._isBlocking = value;
  24873. },
  24874. enumerable: true,
  24875. configurable: true
  24876. });
  24877. Object.defineProperty(Texture.prototype, "samplingMode", {
  24878. get: function () {
  24879. return this._samplingMode;
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. Texture.prototype.updateURL = function (url) {
  24885. this.url = url;
  24886. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24887. this.delayLoad();
  24888. };
  24889. Texture.prototype.delayLoad = function () {
  24890. var _this = this;
  24891. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24892. return;
  24893. }
  24894. var scene = this.getScene();
  24895. if (!scene) {
  24896. return;
  24897. }
  24898. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24899. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24900. if (!this._texture) {
  24901. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24902. if (this._deleteBuffer) {
  24903. delete this._buffer;
  24904. }
  24905. }
  24906. else {
  24907. if (this._texture.isReady) {
  24908. BABYLON.Tools.SetImmediate(function () {
  24909. if (!_this._delayedOnLoad) {
  24910. return;
  24911. }
  24912. _this._delayedOnLoad();
  24913. });
  24914. }
  24915. else {
  24916. if (this._delayedOnLoad) {
  24917. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24918. }
  24919. }
  24920. }
  24921. };
  24922. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24923. if (!this._texture) {
  24924. return;
  24925. }
  24926. var scene = this.getScene();
  24927. if (!scene) {
  24928. return;
  24929. }
  24930. this._samplingMode = samplingMode;
  24931. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24932. };
  24933. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24934. x *= this.uScale;
  24935. y *= this.vScale;
  24936. x -= 0.5 * this.uScale;
  24937. y -= 0.5 * this.vScale;
  24938. z -= 0.5;
  24939. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24940. t.x += 0.5 * this.uScale + this.uOffset;
  24941. t.y += 0.5 * this.vScale + this.vOffset;
  24942. t.z += 0.5;
  24943. };
  24944. Texture.prototype.getTextureMatrix = function () {
  24945. var _this = this;
  24946. if (this.uOffset === this._cachedUOffset &&
  24947. this.vOffset === this._cachedVOffset &&
  24948. this.uScale === this._cachedUScale &&
  24949. this.vScale === this._cachedVScale &&
  24950. this.uAng === this._cachedUAng &&
  24951. this.vAng === this._cachedVAng &&
  24952. this.wAng === this._cachedWAng) {
  24953. return this._cachedTextureMatrix;
  24954. }
  24955. this._cachedUOffset = this.uOffset;
  24956. this._cachedVOffset = this.vOffset;
  24957. this._cachedUScale = this.uScale;
  24958. this._cachedVScale = this.vScale;
  24959. this._cachedUAng = this.uAng;
  24960. this._cachedVAng = this.vAng;
  24961. this._cachedWAng = this.wAng;
  24962. if (!this._cachedTextureMatrix) {
  24963. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24964. this._rowGenerationMatrix = new BABYLON.Matrix();
  24965. this._t0 = BABYLON.Vector3.Zero();
  24966. this._t1 = BABYLON.Vector3.Zero();
  24967. this._t2 = BABYLON.Vector3.Zero();
  24968. }
  24969. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24970. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24971. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24972. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24973. this._t1.subtractInPlace(this._t0);
  24974. this._t2.subtractInPlace(this._t0);
  24975. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24976. this._cachedTextureMatrix.m[0] = this._t1.x;
  24977. this._cachedTextureMatrix.m[1] = this._t1.y;
  24978. this._cachedTextureMatrix.m[2] = this._t1.z;
  24979. this._cachedTextureMatrix.m[4] = this._t2.x;
  24980. this._cachedTextureMatrix.m[5] = this._t2.y;
  24981. this._cachedTextureMatrix.m[6] = this._t2.z;
  24982. this._cachedTextureMatrix.m[8] = this._t0.x;
  24983. this._cachedTextureMatrix.m[9] = this._t0.y;
  24984. this._cachedTextureMatrix.m[10] = this._t0.z;
  24985. var scene = this.getScene();
  24986. if (!scene) {
  24987. return this._cachedTextureMatrix;
  24988. }
  24989. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24990. return mat.hasTexture(_this);
  24991. });
  24992. return this._cachedTextureMatrix;
  24993. };
  24994. Texture.prototype.getReflectionTextureMatrix = function () {
  24995. var _this = this;
  24996. var scene = this.getScene();
  24997. if (!scene) {
  24998. return this._cachedTextureMatrix;
  24999. }
  25000. if (this.uOffset === this._cachedUOffset &&
  25001. this.vOffset === this._cachedVOffset &&
  25002. this.uScale === this._cachedUScale &&
  25003. this.vScale === this._cachedVScale &&
  25004. this.coordinatesMode === this._cachedCoordinatesMode) {
  25005. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25006. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25007. return this._cachedTextureMatrix;
  25008. }
  25009. }
  25010. else {
  25011. return this._cachedTextureMatrix;
  25012. }
  25013. }
  25014. if (!this._cachedTextureMatrix) {
  25015. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25016. }
  25017. if (!this._projectionModeMatrix) {
  25018. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25019. }
  25020. this._cachedUOffset = this.uOffset;
  25021. this._cachedVOffset = this.vOffset;
  25022. this._cachedUScale = this.uScale;
  25023. this._cachedVScale = this.vScale;
  25024. this._cachedCoordinatesMode = this.coordinatesMode;
  25025. switch (this.coordinatesMode) {
  25026. case Texture.PLANAR_MODE:
  25027. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25028. this._cachedTextureMatrix[0] = this.uScale;
  25029. this._cachedTextureMatrix[5] = this.vScale;
  25030. this._cachedTextureMatrix[12] = this.uOffset;
  25031. this._cachedTextureMatrix[13] = this.vOffset;
  25032. break;
  25033. case Texture.PROJECTION_MODE:
  25034. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25035. this._projectionModeMatrix.m[0] = 0.5;
  25036. this._projectionModeMatrix.m[5] = -0.5;
  25037. this._projectionModeMatrix.m[10] = 0.0;
  25038. this._projectionModeMatrix.m[12] = 0.5;
  25039. this._projectionModeMatrix.m[13] = 0.5;
  25040. this._projectionModeMatrix.m[14] = 1.0;
  25041. this._projectionModeMatrix.m[15] = 1.0;
  25042. var projectionMatrix = scene.getProjectionMatrix();
  25043. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25044. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25045. break;
  25046. default:
  25047. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25048. break;
  25049. }
  25050. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25051. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25052. });
  25053. return this._cachedTextureMatrix;
  25054. };
  25055. Texture.prototype.clone = function () {
  25056. var _this = this;
  25057. return BABYLON.SerializationHelper.Clone(function () {
  25058. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25059. }, this);
  25060. };
  25061. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25062. get: function () {
  25063. if (!this._onLoadObservable) {
  25064. this._onLoadObservable = new BABYLON.Observable();
  25065. }
  25066. return this._onLoadObservable;
  25067. },
  25068. enumerable: true,
  25069. configurable: true
  25070. });
  25071. Texture.prototype.serialize = function () {
  25072. var serializationObject = _super.prototype.serialize.call(this);
  25073. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25074. serializationObject.base64String = this._buffer;
  25075. serializationObject.name = serializationObject.name.replace("data:", "");
  25076. }
  25077. return serializationObject;
  25078. };
  25079. Texture.prototype.getClassName = function () {
  25080. return "Texture";
  25081. };
  25082. Texture.prototype.dispose = function () {
  25083. _super.prototype.dispose.call(this);
  25084. if (this.onLoadObservable) {
  25085. this.onLoadObservable.clear();
  25086. this._onLoadObservable = null;
  25087. }
  25088. this._delayedOnLoad = null;
  25089. this._delayedOnError = null;
  25090. };
  25091. // Statics
  25092. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25093. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25094. if (onLoad === void 0) { onLoad = null; }
  25095. if (onError === void 0) { onError = null; }
  25096. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25097. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25098. };
  25099. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25100. if (parsedTexture.customType) {
  25101. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25102. // Update Sampling Mode
  25103. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25104. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25105. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25106. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25107. }
  25108. }
  25109. return parsedCustomTexture;
  25110. }
  25111. if (parsedTexture.isCube) {
  25112. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25113. }
  25114. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25115. return null;
  25116. }
  25117. var texture = BABYLON.SerializationHelper.Parse(function () {
  25118. var generateMipMaps = true;
  25119. if (parsedTexture.noMipmap) {
  25120. generateMipMaps = false;
  25121. }
  25122. if (parsedTexture.mirrorPlane) {
  25123. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25124. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25125. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25126. return mirrorTexture;
  25127. }
  25128. else if (parsedTexture.isRenderTarget) {
  25129. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25130. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25131. return renderTargetTexture;
  25132. }
  25133. else {
  25134. var texture;
  25135. if (parsedTexture.base64String) {
  25136. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25137. }
  25138. else {
  25139. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25140. }
  25141. return texture;
  25142. }
  25143. }, parsedTexture, scene);
  25144. // Update Sampling Mode
  25145. if (parsedTexture.samplingMode) {
  25146. var sampling = parsedTexture.samplingMode;
  25147. if (texture._samplingMode !== sampling) {
  25148. texture.updateSamplingMode(sampling);
  25149. }
  25150. }
  25151. // Animations
  25152. if (parsedTexture.animations) {
  25153. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25154. var parsedAnimation = parsedTexture.animations[animationIndex];
  25155. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25156. }
  25157. }
  25158. return texture;
  25159. };
  25160. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25161. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25162. if (noMipmap === void 0) { noMipmap = false; }
  25163. if (invertY === void 0) { invertY = true; }
  25164. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25165. if (onLoad === void 0) { onLoad = null; }
  25166. if (onError === void 0) { onError = null; }
  25167. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25168. if (name.substr(0, 5) !== "data:") {
  25169. name = "data:" + name;
  25170. }
  25171. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25172. };
  25173. // Constants
  25174. Texture.NEAREST_SAMPLINGMODE = 1;
  25175. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25176. Texture.BILINEAR_SAMPLINGMODE = 2;
  25177. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25178. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25179. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25180. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25181. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25182. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25183. Texture.NEAREST_LINEAR = 7;
  25184. Texture.NEAREST_NEAREST = 8;
  25185. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25186. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25187. Texture.LINEAR_LINEAR = 11;
  25188. Texture.LINEAR_NEAREST = 12;
  25189. Texture.EXPLICIT_MODE = 0;
  25190. Texture.SPHERICAL_MODE = 1;
  25191. Texture.PLANAR_MODE = 2;
  25192. Texture.CUBIC_MODE = 3;
  25193. Texture.PROJECTION_MODE = 4;
  25194. Texture.SKYBOX_MODE = 5;
  25195. Texture.INVCUBIC_MODE = 6;
  25196. Texture.EQUIRECTANGULAR_MODE = 7;
  25197. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25198. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25199. Texture.CLAMP_ADDRESSMODE = 0;
  25200. Texture.WRAP_ADDRESSMODE = 1;
  25201. Texture.MIRROR_ADDRESSMODE = 2;
  25202. __decorate([
  25203. BABYLON.serialize()
  25204. ], Texture.prototype, "url", void 0);
  25205. __decorate([
  25206. BABYLON.serialize()
  25207. ], Texture.prototype, "uOffset", void 0);
  25208. __decorate([
  25209. BABYLON.serialize()
  25210. ], Texture.prototype, "vOffset", void 0);
  25211. __decorate([
  25212. BABYLON.serialize()
  25213. ], Texture.prototype, "uScale", void 0);
  25214. __decorate([
  25215. BABYLON.serialize()
  25216. ], Texture.prototype, "vScale", void 0);
  25217. __decorate([
  25218. BABYLON.serialize()
  25219. ], Texture.prototype, "uAng", void 0);
  25220. __decorate([
  25221. BABYLON.serialize()
  25222. ], Texture.prototype, "vAng", void 0);
  25223. __decorate([
  25224. BABYLON.serialize()
  25225. ], Texture.prototype, "wAng", void 0);
  25226. __decorate([
  25227. BABYLON.serialize()
  25228. ], Texture.prototype, "isBlocking", null);
  25229. return Texture;
  25230. }(BABYLON.BaseTexture));
  25231. BABYLON.Texture = Texture;
  25232. })(BABYLON || (BABYLON = {}));
  25233. //# sourceMappingURL=babylon.texture.js.map
  25234. var BABYLON;
  25235. (function (BABYLON) {
  25236. var _InstancesBatch = /** @class */ (function () {
  25237. function _InstancesBatch() {
  25238. this.mustReturn = false;
  25239. this.visibleInstances = new Array();
  25240. this.renderSelf = new Array();
  25241. }
  25242. return _InstancesBatch;
  25243. }());
  25244. BABYLON._InstancesBatch = _InstancesBatch;
  25245. var Mesh = /** @class */ (function (_super) {
  25246. __extends(Mesh, _super);
  25247. /**
  25248. * @constructor
  25249. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25250. * @param {Scene} scene The scene to add this mesh to.
  25251. * @param {Node} parent The parent of this mesh, if it has one
  25252. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25253. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25254. * When false, achieved by calling a clone(), also passing False.
  25255. * This will make creation of children, recursive.
  25256. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25257. */
  25258. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25259. if (scene === void 0) { scene = null; }
  25260. if (parent === void 0) { parent = null; }
  25261. if (source === void 0) { source = null; }
  25262. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25263. var _this = _super.call(this, name, scene) || this;
  25264. // Events
  25265. /**
  25266. * An event triggered before rendering the mesh
  25267. * @type {BABYLON.Observable}
  25268. */
  25269. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25270. /**
  25271. * An event triggered after rendering the mesh
  25272. * @type {BABYLON.Observable}
  25273. */
  25274. _this.onAfterRenderObservable = new BABYLON.Observable();
  25275. /**
  25276. * An event triggered before drawing the mesh
  25277. * @type {BABYLON.Observable}
  25278. */
  25279. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25280. // Members
  25281. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25282. _this.instances = new Array();
  25283. _this._LODLevels = new Array();
  25284. _this._visibleInstances = {};
  25285. _this._renderIdForInstances = new Array();
  25286. _this._batchCache = new _InstancesBatch();
  25287. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25288. // Use by builder only to know what orientation were the mesh build in.
  25289. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25290. _this.overrideMaterialSideOrientation = null;
  25291. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25292. // Will be used to save a source mesh reference, If any
  25293. _this._source = null;
  25294. scene = _this.getScene();
  25295. if (source) {
  25296. // Source mesh
  25297. _this._source = source;
  25298. // Geometry
  25299. if (source._geometry) {
  25300. source._geometry.applyToMesh(_this);
  25301. }
  25302. // Deep copy
  25303. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25304. // Metadata
  25305. if (source.metadata && source.metadata.clone) {
  25306. _this.metadata = source.metadata.clone();
  25307. }
  25308. else {
  25309. _this.metadata = source.metadata;
  25310. }
  25311. // Tags
  25312. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25313. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25314. }
  25315. // Parent
  25316. _this.parent = source.parent;
  25317. // Pivot
  25318. _this.setPivotMatrix(source.getPivotMatrix());
  25319. _this.id = name + "." + source.id;
  25320. // Material
  25321. _this.material = source.material;
  25322. var index;
  25323. if (!doNotCloneChildren) {
  25324. // Children
  25325. var directDescendants = source.getDescendants(true);
  25326. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25327. var child = directDescendants[index_1];
  25328. if (child.clone) {
  25329. child.clone(name + "." + child.name, _this);
  25330. }
  25331. }
  25332. }
  25333. // Physics clone
  25334. var physicsEngine = _this.getScene().getPhysicsEngine();
  25335. if (clonePhysicsImpostor && physicsEngine) {
  25336. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25337. if (impostor) {
  25338. _this.physicsImpostor = impostor.clone(_this);
  25339. }
  25340. }
  25341. // Particles
  25342. for (index = 0; index < scene.particleSystems.length; index++) {
  25343. var system = scene.particleSystems[index];
  25344. if (system.emitter === source) {
  25345. system.clone(system.name, _this);
  25346. }
  25347. }
  25348. _this.computeWorldMatrix(true);
  25349. }
  25350. // Parent
  25351. if (parent !== null) {
  25352. _this.parent = parent;
  25353. }
  25354. return _this;
  25355. }
  25356. Object.defineProperty(Mesh, "FRONTSIDE", {
  25357. /**
  25358. * Mesh side orientation : usually the external or front surface
  25359. */
  25360. get: function () {
  25361. return Mesh._FRONTSIDE;
  25362. },
  25363. enumerable: true,
  25364. configurable: true
  25365. });
  25366. Object.defineProperty(Mesh, "BACKSIDE", {
  25367. /**
  25368. * Mesh side orientation : usually the internal or back surface
  25369. */
  25370. get: function () {
  25371. return Mesh._BACKSIDE;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25377. /**
  25378. * Mesh side orientation : both internal and external or front and back surfaces
  25379. */
  25380. get: function () {
  25381. return Mesh._DOUBLESIDE;
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25387. /**
  25388. * Mesh side orientation : by default, `FRONTSIDE`
  25389. */
  25390. get: function () {
  25391. return Mesh._DEFAULTSIDE;
  25392. },
  25393. enumerable: true,
  25394. configurable: true
  25395. });
  25396. Object.defineProperty(Mesh, "NO_CAP", {
  25397. /**
  25398. * Mesh cap setting : no cap
  25399. */
  25400. get: function () {
  25401. return Mesh._NO_CAP;
  25402. },
  25403. enumerable: true,
  25404. configurable: true
  25405. });
  25406. Object.defineProperty(Mesh, "CAP_START", {
  25407. /**
  25408. * Mesh cap setting : one cap at the beginning of the mesh
  25409. */
  25410. get: function () {
  25411. return Mesh._CAP_START;
  25412. },
  25413. enumerable: true,
  25414. configurable: true
  25415. });
  25416. Object.defineProperty(Mesh, "CAP_END", {
  25417. /**
  25418. * Mesh cap setting : one cap at the end of the mesh
  25419. */
  25420. get: function () {
  25421. return Mesh._CAP_END;
  25422. },
  25423. enumerable: true,
  25424. configurable: true
  25425. });
  25426. Object.defineProperty(Mesh, "CAP_ALL", {
  25427. /**
  25428. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25429. */
  25430. get: function () {
  25431. return Mesh._CAP_ALL;
  25432. },
  25433. enumerable: true,
  25434. configurable: true
  25435. });
  25436. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25437. set: function (callback) {
  25438. if (this._onBeforeDrawObserver) {
  25439. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25440. }
  25441. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25442. },
  25443. enumerable: true,
  25444. configurable: true
  25445. });
  25446. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25447. get: function () {
  25448. return this._morphTargetManager;
  25449. },
  25450. set: function (value) {
  25451. if (this._morphTargetManager === value) {
  25452. return;
  25453. }
  25454. this._morphTargetManager = value;
  25455. this._syncGeometryWithMorphTargetManager();
  25456. },
  25457. enumerable: true,
  25458. configurable: true
  25459. });
  25460. Object.defineProperty(Mesh.prototype, "source", {
  25461. get: function () {
  25462. return this._source;
  25463. },
  25464. enumerable: true,
  25465. configurable: true
  25466. });
  25467. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25468. get: function () {
  25469. return this._unIndexed;
  25470. },
  25471. set: function (value) {
  25472. if (this._unIndexed !== value) {
  25473. this._unIndexed = value;
  25474. this._markSubMeshesAsAttributesDirty();
  25475. }
  25476. },
  25477. enumerable: true,
  25478. configurable: true
  25479. });
  25480. // Methods
  25481. /**
  25482. * Returns the string "Mesh".
  25483. */
  25484. Mesh.prototype.getClassName = function () {
  25485. return "Mesh";
  25486. };
  25487. /**
  25488. * Returns a string.
  25489. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25490. */
  25491. Mesh.prototype.toString = function (fullDetails) {
  25492. var ret = _super.prototype.toString.call(this, fullDetails);
  25493. ret += ", n vertices: " + this.getTotalVertices();
  25494. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25495. if (this.animations) {
  25496. for (var i = 0; i < this.animations.length; i++) {
  25497. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25498. }
  25499. }
  25500. if (fullDetails) {
  25501. if (this._geometry) {
  25502. var ib = this.getIndices();
  25503. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25504. if (vb && ib) {
  25505. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25506. }
  25507. }
  25508. else {
  25509. ret += ", flat shading: UNKNOWN";
  25510. }
  25511. }
  25512. return ret;
  25513. };
  25514. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25515. /**
  25516. * True if the mesh has some Levels Of Details (LOD).
  25517. * Returns a boolean.
  25518. */
  25519. get: function () {
  25520. return this._LODLevels.length > 0;
  25521. },
  25522. enumerable: true,
  25523. configurable: true
  25524. });
  25525. /**
  25526. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25527. * @returns an array of {BABYLON.MeshLODLevel}
  25528. */
  25529. Mesh.prototype.getLODLevels = function () {
  25530. return this._LODLevels;
  25531. };
  25532. Mesh.prototype._sortLODLevels = function () {
  25533. this._LODLevels.sort(function (a, b) {
  25534. if (a.distance < b.distance) {
  25535. return 1;
  25536. }
  25537. if (a.distance > b.distance) {
  25538. return -1;
  25539. }
  25540. return 0;
  25541. });
  25542. };
  25543. /**
  25544. * Add a mesh as LOD level triggered at the given distance.
  25545. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25546. * @param {number} distance The distance from the center of the object to show this level
  25547. * @param {Mesh} mesh The mesh to be added as LOD level
  25548. * @return {Mesh} This mesh (for chaining)
  25549. */
  25550. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25551. if (mesh && mesh._masterMesh) {
  25552. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25553. return this;
  25554. }
  25555. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25556. this._LODLevels.push(level);
  25557. if (mesh) {
  25558. mesh._masterMesh = this;
  25559. }
  25560. this._sortLODLevels();
  25561. return this;
  25562. };
  25563. /**
  25564. * Returns the LOD level mesh at the passed distance or null if not found.
  25565. * It is related to the method `addLODLevel(distance, mesh)`.
  25566. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25567. * Returns an object Mesh or `null`.
  25568. */
  25569. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25570. for (var index = 0; index < this._LODLevels.length; index++) {
  25571. var level = this._LODLevels[index];
  25572. if (level.distance === distance) {
  25573. return level.mesh;
  25574. }
  25575. }
  25576. return null;
  25577. };
  25578. /**
  25579. * Remove a mesh from the LOD array
  25580. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25581. * @param {Mesh} mesh The mesh to be removed.
  25582. * @return {Mesh} This mesh (for chaining)
  25583. */
  25584. Mesh.prototype.removeLODLevel = function (mesh) {
  25585. for (var index = 0; index < this._LODLevels.length; index++) {
  25586. if (this._LODLevels[index].mesh === mesh) {
  25587. this._LODLevels.splice(index, 1);
  25588. if (mesh) {
  25589. mesh._masterMesh = null;
  25590. }
  25591. }
  25592. }
  25593. this._sortLODLevels();
  25594. return this;
  25595. };
  25596. /**
  25597. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25598. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25599. */
  25600. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25601. if (!this._LODLevels || this._LODLevels.length === 0) {
  25602. return this;
  25603. }
  25604. var bSphere;
  25605. if (boundingSphere) {
  25606. bSphere = boundingSphere;
  25607. }
  25608. else {
  25609. var boundingInfo = this.getBoundingInfo();
  25610. bSphere = boundingInfo.boundingSphere;
  25611. }
  25612. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25613. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25614. if (this.onLODLevelSelection) {
  25615. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25616. }
  25617. return this;
  25618. }
  25619. for (var index = 0; index < this._LODLevels.length; index++) {
  25620. var level = this._LODLevels[index];
  25621. if (level.distance < distanceToCamera) {
  25622. if (level.mesh) {
  25623. level.mesh._preActivate();
  25624. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25625. }
  25626. if (this.onLODLevelSelection) {
  25627. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25628. }
  25629. return level.mesh;
  25630. }
  25631. }
  25632. if (this.onLODLevelSelection) {
  25633. this.onLODLevelSelection(distanceToCamera, this, this);
  25634. }
  25635. return this;
  25636. };
  25637. Object.defineProperty(Mesh.prototype, "geometry", {
  25638. /**
  25639. * Returns the mesh internal Geometry object.
  25640. */
  25641. get: function () {
  25642. return this._geometry;
  25643. },
  25644. enumerable: true,
  25645. configurable: true
  25646. });
  25647. /**
  25648. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25649. */
  25650. Mesh.prototype.getTotalVertices = function () {
  25651. if (this._geometry === null || this._geometry === undefined) {
  25652. return 0;
  25653. }
  25654. return this._geometry.getTotalVertices();
  25655. };
  25656. /**
  25657. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25658. * 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.
  25659. * You can force the copy with forceCopy === true
  25660. * Returns null if the mesh has no geometry or no vertex buffer.
  25661. * Possible `kind` values :
  25662. * - BABYLON.VertexBuffer.PositionKind
  25663. * - BABYLON.VertexBuffer.UVKind
  25664. * - BABYLON.VertexBuffer.UV2Kind
  25665. * - BABYLON.VertexBuffer.UV3Kind
  25666. * - BABYLON.VertexBuffer.UV4Kind
  25667. * - BABYLON.VertexBuffer.UV5Kind
  25668. * - BABYLON.VertexBuffer.UV6Kind
  25669. * - BABYLON.VertexBuffer.ColorKind
  25670. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25671. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25672. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25673. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25674. */
  25675. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25676. if (!this._geometry) {
  25677. return null;
  25678. }
  25679. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25680. };
  25681. /**
  25682. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25683. * Returns `null` if the mesh has no geometry.
  25684. * Possible `kind` values :
  25685. * - BABYLON.VertexBuffer.PositionKind
  25686. * - BABYLON.VertexBuffer.UVKind
  25687. * - BABYLON.VertexBuffer.UV2Kind
  25688. * - BABYLON.VertexBuffer.UV3Kind
  25689. * - BABYLON.VertexBuffer.UV4Kind
  25690. * - BABYLON.VertexBuffer.UV5Kind
  25691. * - BABYLON.VertexBuffer.UV6Kind
  25692. * - BABYLON.VertexBuffer.ColorKind
  25693. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25694. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25695. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25696. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25697. */
  25698. Mesh.prototype.getVertexBuffer = function (kind) {
  25699. if (!this._geometry) {
  25700. return null;
  25701. }
  25702. return this._geometry.getVertexBuffer(kind);
  25703. };
  25704. /**
  25705. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25706. * Possible `kind` values :
  25707. * - BABYLON.VertexBuffer.PositionKind
  25708. * - BABYLON.VertexBuffer.UVKind
  25709. * - BABYLON.VertexBuffer.UV2Kind
  25710. * - BABYLON.VertexBuffer.UV3Kind
  25711. * - BABYLON.VertexBuffer.UV4Kind
  25712. * - BABYLON.VertexBuffer.UV5Kind
  25713. * - BABYLON.VertexBuffer.UV6Kind
  25714. * - BABYLON.VertexBuffer.ColorKind
  25715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25719. */
  25720. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25721. if (!this._geometry) {
  25722. if (this._delayInfo) {
  25723. return this._delayInfo.indexOf(kind) !== -1;
  25724. }
  25725. return false;
  25726. }
  25727. return this._geometry.isVerticesDataPresent(kind);
  25728. };
  25729. /**
  25730. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25731. * Possible `kind` values :
  25732. * - BABYLON.VertexBuffer.PositionKind
  25733. * - BABYLON.VertexBuffer.UVKind
  25734. * - BABYLON.VertexBuffer.UV2Kind
  25735. * - BABYLON.VertexBuffer.UV3Kind
  25736. * - BABYLON.VertexBuffer.UV4Kind
  25737. * - BABYLON.VertexBuffer.UV5Kind
  25738. * - BABYLON.VertexBuffer.UV6Kind
  25739. * - BABYLON.VertexBuffer.ColorKind
  25740. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25741. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25742. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25743. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25744. */
  25745. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25746. if (!this._geometry) {
  25747. if (this._delayInfo) {
  25748. return this._delayInfo.indexOf(kind) !== -1;
  25749. }
  25750. return false;
  25751. }
  25752. return this._geometry.isVertexBufferUpdatable(kind);
  25753. };
  25754. /**
  25755. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25756. * Possible `kind` values :
  25757. * - BABYLON.VertexBuffer.PositionKind
  25758. * - BABYLON.VertexBuffer.UVKind
  25759. * - BABYLON.VertexBuffer.UV2Kind
  25760. * - BABYLON.VertexBuffer.UV3Kind
  25761. * - BABYLON.VertexBuffer.UV4Kind
  25762. * - BABYLON.VertexBuffer.UV5Kind
  25763. * - BABYLON.VertexBuffer.UV6Kind
  25764. * - BABYLON.VertexBuffer.ColorKind
  25765. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25766. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25767. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25768. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25769. */
  25770. Mesh.prototype.getVerticesDataKinds = function () {
  25771. if (!this._geometry) {
  25772. var result = new Array();
  25773. if (this._delayInfo) {
  25774. this._delayInfo.forEach(function (kind, index, array) {
  25775. result.push(kind);
  25776. });
  25777. }
  25778. return result;
  25779. }
  25780. return this._geometry.getVerticesDataKinds();
  25781. };
  25782. /**
  25783. * Returns a positive integer : the total number of indices in this mesh geometry.
  25784. * Returns zero if the mesh has no geometry.
  25785. */
  25786. Mesh.prototype.getTotalIndices = function () {
  25787. if (!this._geometry) {
  25788. return 0;
  25789. }
  25790. return this._geometry.getTotalIndices();
  25791. };
  25792. /**
  25793. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25794. * 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.
  25795. * Returns an empty array if the mesh has no geometry.
  25796. */
  25797. Mesh.prototype.getIndices = function (copyWhenShared) {
  25798. if (!this._geometry) {
  25799. return [];
  25800. }
  25801. return this._geometry.getIndices(copyWhenShared);
  25802. };
  25803. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25804. get: function () {
  25805. return this._masterMesh !== null && this._masterMesh !== undefined;
  25806. },
  25807. enumerable: true,
  25808. configurable: true
  25809. });
  25810. /**
  25811. * Determine if the current mesh is ready to be rendered
  25812. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25813. * @returns true if all associated assets are ready (material, textures, shaders)
  25814. */
  25815. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25816. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25817. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25818. return false;
  25819. }
  25820. if (!_super.prototype.isReady.call(this)) {
  25821. return false;
  25822. }
  25823. if (!this.subMeshes || this.subMeshes.length === 0) {
  25824. return true;
  25825. }
  25826. var engine = this.getEngine();
  25827. var scene = this.getScene();
  25828. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25829. this.computeWorldMatrix();
  25830. var mat = this.material || scene.defaultMaterial;
  25831. if (mat) {
  25832. if (mat.storeEffectOnSubMeshes) {
  25833. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25834. var subMesh = _a[_i];
  25835. var effectiveMaterial = subMesh.getMaterial();
  25836. if (effectiveMaterial) {
  25837. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25838. return false;
  25839. }
  25840. }
  25841. }
  25842. }
  25843. else {
  25844. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25845. return false;
  25846. }
  25847. }
  25848. }
  25849. // Shadows
  25850. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25851. var light = _c[_b];
  25852. var generator = light.getShadowGenerator();
  25853. if (generator) {
  25854. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25855. var subMesh = _e[_d];
  25856. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25857. return false;
  25858. }
  25859. }
  25860. }
  25861. }
  25862. // LOD
  25863. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25864. var lod = _g[_f];
  25865. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25866. return false;
  25867. }
  25868. }
  25869. return true;
  25870. };
  25871. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25872. /**
  25873. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25874. * This property is pertinent only for updatable parametric shapes.
  25875. */
  25876. get: function () {
  25877. return this._areNormalsFrozen;
  25878. },
  25879. enumerable: true,
  25880. configurable: true
  25881. });
  25882. /**
  25883. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25884. * It has no effect at all on other shapes.
  25885. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25886. * Returns the Mesh.
  25887. */
  25888. Mesh.prototype.freezeNormals = function () {
  25889. this._areNormalsFrozen = true;
  25890. return this;
  25891. };
  25892. /**
  25893. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25894. * It has no effect at all on other shapes.
  25895. * It reactivates the mesh normals computation if it was previously frozen.
  25896. * Returns the Mesh.
  25897. */
  25898. Mesh.prototype.unfreezeNormals = function () {
  25899. this._areNormalsFrozen = false;
  25900. return this;
  25901. };
  25902. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25903. /**
  25904. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25905. */
  25906. set: function (count) {
  25907. this._overridenInstanceCount = count;
  25908. },
  25909. enumerable: true,
  25910. configurable: true
  25911. });
  25912. // Methods
  25913. Mesh.prototype._preActivate = function () {
  25914. var sceneRenderId = this.getScene().getRenderId();
  25915. if (this._preActivateId === sceneRenderId) {
  25916. return this;
  25917. }
  25918. this._preActivateId = sceneRenderId;
  25919. this._visibleInstances = null;
  25920. return this;
  25921. };
  25922. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25923. if (this._visibleInstances) {
  25924. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25925. }
  25926. return this;
  25927. };
  25928. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25929. if (!this._visibleInstances) {
  25930. this._visibleInstances = {};
  25931. this._visibleInstances.defaultRenderId = renderId;
  25932. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25933. }
  25934. if (!this._visibleInstances[renderId]) {
  25935. this._visibleInstances[renderId] = new Array();
  25936. }
  25937. this._visibleInstances[renderId].push(instance);
  25938. return this;
  25939. };
  25940. /**
  25941. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25942. * This means the mesh underlying bounding box and sphere are recomputed.
  25943. * Returns the Mesh.
  25944. */
  25945. Mesh.prototype.refreshBoundingInfo = function () {
  25946. return this._refreshBoundingInfo(false);
  25947. };
  25948. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25949. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25950. return this;
  25951. }
  25952. var data = this._getPositionData(applySkeleton);
  25953. if (data) {
  25954. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25955. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25956. }
  25957. if (this.subMeshes) {
  25958. for (var index = 0; index < this.subMeshes.length; index++) {
  25959. this.subMeshes[index].refreshBoundingInfo();
  25960. }
  25961. }
  25962. this._updateBoundingInfo();
  25963. return this;
  25964. };
  25965. Mesh.prototype._getPositionData = function (applySkeleton) {
  25966. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25967. if (data && applySkeleton && this.skeleton) {
  25968. data = BABYLON.Tools.Slice(data);
  25969. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25970. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25971. if (matricesWeightsData && matricesIndicesData) {
  25972. var needExtras = this.numBoneInfluencers > 4;
  25973. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25974. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25975. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25976. var tempVector = BABYLON.Tmp.Vector3[0];
  25977. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25978. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25979. var matWeightIdx = 0;
  25980. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25981. finalMatrix.reset();
  25982. var inf;
  25983. var weight;
  25984. for (inf = 0; inf < 4; inf++) {
  25985. weight = matricesWeightsData[matWeightIdx + inf];
  25986. if (weight <= 0)
  25987. break;
  25988. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25989. finalMatrix.addToSelf(tempMatrix);
  25990. }
  25991. if (needExtras) {
  25992. for (inf = 0; inf < 4; inf++) {
  25993. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25994. if (weight <= 0)
  25995. break;
  25996. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25997. finalMatrix.addToSelf(tempMatrix);
  25998. }
  25999. }
  26000. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26001. tempVector.toArray(data, index);
  26002. }
  26003. }
  26004. }
  26005. return data;
  26006. };
  26007. Mesh.prototype._createGlobalSubMesh = function (force) {
  26008. var totalVertices = this.getTotalVertices();
  26009. if (!totalVertices || !this.getIndices()) {
  26010. return null;
  26011. }
  26012. // Check if we need to recreate the submeshes
  26013. if (this.subMeshes && this.subMeshes.length > 0) {
  26014. var ib = this.getIndices();
  26015. if (!ib) {
  26016. return null;
  26017. }
  26018. var totalIndices = ib.length;
  26019. var needToRecreate = false;
  26020. if (force) {
  26021. needToRecreate = true;
  26022. }
  26023. else {
  26024. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26025. var submesh = _a[_i];
  26026. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26027. needToRecreate = true;
  26028. break;
  26029. }
  26030. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26031. needToRecreate = true;
  26032. break;
  26033. }
  26034. }
  26035. }
  26036. if (!needToRecreate) {
  26037. return this.subMeshes[0];
  26038. }
  26039. }
  26040. this.releaseSubMeshes();
  26041. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26042. };
  26043. Mesh.prototype.subdivide = function (count) {
  26044. if (count < 1) {
  26045. return;
  26046. }
  26047. var totalIndices = this.getTotalIndices();
  26048. var subdivisionSize = (totalIndices / count) | 0;
  26049. var offset = 0;
  26050. // Ensure that subdivisionSize is a multiple of 3
  26051. while (subdivisionSize % 3 !== 0) {
  26052. subdivisionSize++;
  26053. }
  26054. this.releaseSubMeshes();
  26055. for (var index = 0; index < count; index++) {
  26056. if (offset >= totalIndices) {
  26057. break;
  26058. }
  26059. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26060. offset += subdivisionSize;
  26061. }
  26062. this.synchronizeInstances();
  26063. };
  26064. /**
  26065. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26066. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26067. * The `data` are either a numeric array either a Float32Array.
  26068. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26069. * 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).
  26070. * Note that a new underlying VertexBuffer object is created each call.
  26071. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26072. *
  26073. * Possible `kind` values :
  26074. * - BABYLON.VertexBuffer.PositionKind
  26075. * - BABYLON.VertexBuffer.UVKind
  26076. * - BABYLON.VertexBuffer.UV2Kind
  26077. * - BABYLON.VertexBuffer.UV3Kind
  26078. * - BABYLON.VertexBuffer.UV4Kind
  26079. * - BABYLON.VertexBuffer.UV5Kind
  26080. * - BABYLON.VertexBuffer.UV6Kind
  26081. * - BABYLON.VertexBuffer.ColorKind
  26082. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26083. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26084. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26085. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26086. *
  26087. * Returns the Mesh.
  26088. */
  26089. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26090. if (updatable === void 0) { updatable = false; }
  26091. if (!this._geometry) {
  26092. var vertexData = new BABYLON.VertexData();
  26093. vertexData.set(data, kind);
  26094. var scene = this.getScene();
  26095. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26096. }
  26097. else {
  26098. this._geometry.setVerticesData(kind, data, updatable, stride);
  26099. }
  26100. return this;
  26101. };
  26102. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26103. if (updatable === void 0) { updatable = true; }
  26104. var vb = this.getVertexBuffer(kind);
  26105. if (!vb || vb.isUpdatable() === updatable) {
  26106. return;
  26107. }
  26108. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26109. };
  26110. /**
  26111. * Sets the mesh VertexBuffer.
  26112. * Returns the Mesh.
  26113. */
  26114. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26115. if (!this._geometry) {
  26116. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26117. }
  26118. this._geometry.setVerticesBuffer(buffer);
  26119. return this;
  26120. };
  26121. /**
  26122. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26123. * If the mesh has no geometry, it is simply returned as it is.
  26124. * The `data` are either a numeric array either a Float32Array.
  26125. * No new underlying VertexBuffer object is created.
  26126. * 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.
  26127. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26128. *
  26129. * Possible `kind` values :
  26130. * - BABYLON.VertexBuffer.PositionKind
  26131. * - BABYLON.VertexBuffer.UVKind
  26132. * - BABYLON.VertexBuffer.UV2Kind
  26133. * - BABYLON.VertexBuffer.UV3Kind
  26134. * - BABYLON.VertexBuffer.UV4Kind
  26135. * - BABYLON.VertexBuffer.UV5Kind
  26136. * - BABYLON.VertexBuffer.UV6Kind
  26137. * - BABYLON.VertexBuffer.ColorKind
  26138. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26139. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26140. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26141. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26142. *
  26143. * Returns the Mesh.
  26144. */
  26145. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26146. if (!this._geometry) {
  26147. return this;
  26148. }
  26149. if (!makeItUnique) {
  26150. this._geometry.updateVerticesData(kind, data, updateExtends);
  26151. }
  26152. else {
  26153. this.makeGeometryUnique();
  26154. this.updateVerticesData(kind, data, updateExtends, false);
  26155. }
  26156. return this;
  26157. };
  26158. /**
  26159. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26160. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26161. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26162. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26163. * Returns the Mesh.
  26164. */
  26165. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26166. if (computeNormals === void 0) { computeNormals = true; }
  26167. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26168. if (!positions) {
  26169. return this;
  26170. }
  26171. positionFunction(positions);
  26172. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26173. if (computeNormals) {
  26174. var indices = this.getIndices();
  26175. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26176. if (!normals) {
  26177. return this;
  26178. }
  26179. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26180. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26181. }
  26182. return this;
  26183. };
  26184. /**
  26185. * Creates a un-shared specific occurence of the geometry for the mesh.
  26186. * Returns the Mesh.
  26187. */
  26188. Mesh.prototype.makeGeometryUnique = function () {
  26189. if (!this._geometry) {
  26190. return this;
  26191. }
  26192. var oldGeometry = this._geometry;
  26193. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26194. oldGeometry.releaseForMesh(this, true);
  26195. geometry.applyToMesh(this);
  26196. return this;
  26197. };
  26198. /**
  26199. * Sets the mesh indices.
  26200. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26201. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26202. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26203. * This method creates a new index buffer each call.
  26204. * Returns the Mesh.
  26205. */
  26206. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26207. if (totalVertices === void 0) { totalVertices = null; }
  26208. if (updatable === void 0) { updatable = false; }
  26209. if (!this._geometry) {
  26210. var vertexData = new BABYLON.VertexData();
  26211. vertexData.indices = indices;
  26212. var scene = this.getScene();
  26213. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26214. }
  26215. else {
  26216. this._geometry.setIndices(indices, totalVertices, updatable);
  26217. }
  26218. return this;
  26219. };
  26220. /**
  26221. * Update the current index buffer
  26222. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26223. * Returns the Mesh.
  26224. */
  26225. Mesh.prototype.updateIndices = function (indices, offset) {
  26226. if (!this._geometry) {
  26227. return this;
  26228. }
  26229. this._geometry.updateIndices(indices, offset);
  26230. return this;
  26231. };
  26232. /**
  26233. * Invert the geometry to move from a right handed system to a left handed one.
  26234. * Returns the Mesh.
  26235. */
  26236. Mesh.prototype.toLeftHanded = function () {
  26237. if (!this._geometry) {
  26238. return this;
  26239. }
  26240. this._geometry.toLeftHanded();
  26241. return this;
  26242. };
  26243. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26244. if (!this._geometry) {
  26245. return this;
  26246. }
  26247. var engine = this.getScene().getEngine();
  26248. // Wireframe
  26249. var indexToBind;
  26250. if (this._unIndexed) {
  26251. indexToBind = null;
  26252. }
  26253. else {
  26254. switch (fillMode) {
  26255. case BABYLON.Material.PointFillMode:
  26256. indexToBind = null;
  26257. break;
  26258. case BABYLON.Material.WireFrameFillMode:
  26259. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26260. break;
  26261. default:
  26262. case BABYLON.Material.TriangleFillMode:
  26263. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26264. break;
  26265. }
  26266. }
  26267. // VBOs
  26268. this._geometry._bind(effect, indexToBind);
  26269. return this;
  26270. };
  26271. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26272. if (alternate === void 0) { alternate = false; }
  26273. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26274. return this;
  26275. }
  26276. this.onBeforeDrawObservable.notifyObservers(this);
  26277. var scene = this.getScene();
  26278. var engine = scene.getEngine();
  26279. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26280. // or triangles as points
  26281. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26282. }
  26283. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26284. // Triangles as wireframe
  26285. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26286. }
  26287. else {
  26288. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26289. }
  26290. if (scene._isAlternateRenderingEnabled && !alternate) {
  26291. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26292. if (!effect || !scene.activeCamera) {
  26293. return this;
  26294. }
  26295. scene._switchToAlternateCameraConfiguration(true);
  26296. this._effectiveMaterial.bindView(effect);
  26297. this._effectiveMaterial.bindViewProjection(effect);
  26298. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26299. this._draw(subMesh, fillMode, instancesCount, true);
  26300. engine.setViewport(scene.activeCamera.viewport);
  26301. scene._switchToAlternateCameraConfiguration(false);
  26302. this._effectiveMaterial.bindView(effect);
  26303. this._effectiveMaterial.bindViewProjection(effect);
  26304. }
  26305. return this;
  26306. };
  26307. /**
  26308. * Registers for this mesh a javascript function called just before the rendering process.
  26309. * This function is passed the current mesh.
  26310. * Return the Mesh.
  26311. */
  26312. Mesh.prototype.registerBeforeRender = function (func) {
  26313. this.onBeforeRenderObservable.add(func);
  26314. return this;
  26315. };
  26316. /**
  26317. * Disposes a previously registered javascript function called before the rendering.
  26318. * This function is passed the current mesh.
  26319. * Returns the Mesh.
  26320. */
  26321. Mesh.prototype.unregisterBeforeRender = function (func) {
  26322. this.onBeforeRenderObservable.removeCallback(func);
  26323. return this;
  26324. };
  26325. /**
  26326. * Registers for this mesh a javascript function called just after the rendering is complete.
  26327. * This function is passed the current mesh.
  26328. * Returns the Mesh.
  26329. */
  26330. Mesh.prototype.registerAfterRender = function (func) {
  26331. this.onAfterRenderObservable.add(func);
  26332. return this;
  26333. };
  26334. /**
  26335. * Disposes a previously registered javascript function called after the rendering.
  26336. * This function is passed the current mesh.
  26337. * Return the Mesh.
  26338. */
  26339. Mesh.prototype.unregisterAfterRender = function (func) {
  26340. this.onAfterRenderObservable.removeCallback(func);
  26341. return this;
  26342. };
  26343. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26344. var scene = this.getScene();
  26345. this._batchCache.mustReturn = false;
  26346. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26347. this._batchCache.visibleInstances[subMeshId] = null;
  26348. if (this._visibleInstances) {
  26349. var currentRenderId = scene.getRenderId();
  26350. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26351. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26352. var selfRenderId = this._renderId;
  26353. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26354. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26355. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26356. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26357. }
  26358. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26359. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26360. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26361. this._batchCache.mustReturn = true;
  26362. return this._batchCache;
  26363. }
  26364. if (currentRenderId !== selfRenderId) {
  26365. this._batchCache.renderSelf[subMeshId] = false;
  26366. }
  26367. }
  26368. this._renderIdForInstances[subMeshId] = currentRenderId;
  26369. }
  26370. return this._batchCache;
  26371. };
  26372. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26373. var visibleInstances = batch.visibleInstances[subMesh._id];
  26374. if (!visibleInstances) {
  26375. return this;
  26376. }
  26377. var matricesCount = visibleInstances.length + 1;
  26378. var bufferSize = matricesCount * 16 * 4;
  26379. var currentInstancesBufferSize = this._instancesBufferSize;
  26380. var instancesBuffer = this._instancesBuffer;
  26381. while (this._instancesBufferSize < bufferSize) {
  26382. this._instancesBufferSize *= 2;
  26383. }
  26384. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26385. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26386. }
  26387. var offset = 0;
  26388. var instancesCount = 0;
  26389. var world = this.getWorldMatrix();
  26390. if (batch.renderSelf[subMesh._id]) {
  26391. world.copyToArray(this._instancesData, offset);
  26392. offset += 16;
  26393. instancesCount++;
  26394. }
  26395. if (visibleInstances) {
  26396. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26397. var instance = visibleInstances[instanceIndex];
  26398. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26399. offset += 16;
  26400. instancesCount++;
  26401. }
  26402. }
  26403. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26404. if (instancesBuffer) {
  26405. instancesBuffer.dispose();
  26406. }
  26407. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26408. this._instancesBuffer = instancesBuffer;
  26409. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26410. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26411. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26412. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26413. }
  26414. else {
  26415. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26416. }
  26417. this._bind(subMesh, effect, fillMode);
  26418. this._draw(subMesh, fillMode, instancesCount);
  26419. engine.unbindInstanceAttributes();
  26420. return this;
  26421. };
  26422. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26423. var scene = this.getScene();
  26424. var engine = scene.getEngine();
  26425. if (hardwareInstancedRendering) {
  26426. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26427. }
  26428. else {
  26429. if (batch.renderSelf[subMesh._id]) {
  26430. // Draw
  26431. if (onBeforeDraw) {
  26432. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26433. }
  26434. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26435. }
  26436. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26437. if (visibleInstancesForSubMesh) {
  26438. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26439. var instance = visibleInstancesForSubMesh[instanceIndex];
  26440. // World
  26441. var world = instance.getWorldMatrix();
  26442. if (onBeforeDraw) {
  26443. onBeforeDraw(true, world, effectiveMaterial);
  26444. }
  26445. // Draw
  26446. this._draw(subMesh, fillMode);
  26447. }
  26448. }
  26449. }
  26450. return this;
  26451. };
  26452. /**
  26453. * Triggers the draw call for the mesh.
  26454. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26455. * Returns the Mesh.
  26456. */
  26457. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26458. this.checkOcclusionQuery();
  26459. if (this._isOccluded) {
  26460. return this;
  26461. }
  26462. var scene = this.getScene();
  26463. // Managing instances
  26464. var batch = this._getInstancesRenderList(subMesh._id);
  26465. if (batch.mustReturn) {
  26466. return this;
  26467. }
  26468. // Checking geometry state
  26469. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26470. return this;
  26471. }
  26472. this.onBeforeRenderObservable.notifyObservers(this);
  26473. var engine = scene.getEngine();
  26474. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26475. // Material
  26476. var material = subMesh.getMaterial();
  26477. if (!material) {
  26478. return this;
  26479. }
  26480. this._effectiveMaterial = material;
  26481. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26482. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26483. return this;
  26484. }
  26485. }
  26486. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26487. return this;
  26488. }
  26489. // Alpha mode
  26490. if (enableAlphaMode) {
  26491. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26492. }
  26493. // Outline - step 1
  26494. var savedDepthWrite = engine.getDepthWrite();
  26495. if (this.renderOutline) {
  26496. engine.setDepthWrite(false);
  26497. scene.getOutlineRenderer().render(subMesh, batch);
  26498. engine.setDepthWrite(savedDepthWrite);
  26499. }
  26500. var effect;
  26501. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26502. effect = subMesh.effect;
  26503. }
  26504. else {
  26505. effect = this._effectiveMaterial.getEffect();
  26506. }
  26507. if (!effect) {
  26508. return this;
  26509. }
  26510. var sideOrientation = this.overrideMaterialSideOrientation;
  26511. if (sideOrientation == null) {
  26512. sideOrientation = this._effectiveMaterial.sideOrientation;
  26513. if (this._getWorldMatrixDeterminant() < 0) {
  26514. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26515. }
  26516. }
  26517. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26518. if (this._effectiveMaterial.forceDepthWrite) {
  26519. engine.setDepthWrite(true);
  26520. }
  26521. // Bind
  26522. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26523. if (!hardwareInstancedRendering) {
  26524. this._bind(subMesh, effect, fillMode);
  26525. }
  26526. var world = this.getWorldMatrix();
  26527. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26528. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26529. }
  26530. else {
  26531. this._effectiveMaterial.bind(world, this);
  26532. }
  26533. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26534. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26535. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26536. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26537. }
  26538. // Draw
  26539. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26540. // Unbind
  26541. this._effectiveMaterial.unbind();
  26542. // Outline - step 2
  26543. if (this.renderOutline && savedDepthWrite) {
  26544. engine.setDepthWrite(true);
  26545. engine.setColorWrite(false);
  26546. scene.getOutlineRenderer().render(subMesh, batch);
  26547. engine.setColorWrite(true);
  26548. }
  26549. // Overlay
  26550. if (this.renderOverlay) {
  26551. var currentMode = engine.getAlphaMode();
  26552. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26553. scene.getOutlineRenderer().render(subMesh, batch, true);
  26554. engine.setAlphaMode(currentMode);
  26555. }
  26556. this.onAfterRenderObservable.notifyObservers(this);
  26557. return this;
  26558. };
  26559. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26560. if (isInstance && effectiveMaterial) {
  26561. effectiveMaterial.bindOnlyWorldMatrix(world);
  26562. }
  26563. };
  26564. /**
  26565. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26566. */
  26567. Mesh.prototype.getEmittedParticleSystems = function () {
  26568. var results = new Array();
  26569. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26570. var particleSystem = this.getScene().particleSystems[index];
  26571. if (particleSystem.emitter === this) {
  26572. results.push(particleSystem);
  26573. }
  26574. }
  26575. return results;
  26576. };
  26577. /**
  26578. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26579. */
  26580. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26581. var results = new Array();
  26582. var descendants = this.getDescendants();
  26583. descendants.push(this);
  26584. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26585. var particleSystem = this.getScene().particleSystems[index];
  26586. var emitter = particleSystem.emitter;
  26587. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26588. results.push(particleSystem);
  26589. }
  26590. }
  26591. return results;
  26592. };
  26593. Mesh.prototype._checkDelayState = function () {
  26594. var scene = this.getScene();
  26595. if (this._geometry) {
  26596. this._geometry.load(scene);
  26597. }
  26598. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26599. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26600. this._queueLoad(scene);
  26601. }
  26602. return this;
  26603. };
  26604. Mesh.prototype._queueLoad = function (scene) {
  26605. var _this = this;
  26606. scene._addPendingData(this);
  26607. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26608. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26609. if (data instanceof ArrayBuffer) {
  26610. _this._delayLoadingFunction(data, _this);
  26611. }
  26612. else {
  26613. _this._delayLoadingFunction(JSON.parse(data), _this);
  26614. }
  26615. _this.instances.forEach(function (instance) {
  26616. instance._syncSubMeshes();
  26617. });
  26618. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26619. scene._removePendingData(_this);
  26620. }, function () { }, scene.database, getBinaryData);
  26621. return this;
  26622. };
  26623. /**
  26624. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26625. */
  26626. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26627. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26628. return false;
  26629. }
  26630. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26631. return false;
  26632. }
  26633. this._checkDelayState();
  26634. return true;
  26635. };
  26636. /**
  26637. * Sets the mesh material by the material or multiMaterial `id` property.
  26638. * The material `id` is a string identifying the material or the multiMaterial.
  26639. * This method returns the Mesh.
  26640. */
  26641. Mesh.prototype.setMaterialByID = function (id) {
  26642. var materials = this.getScene().materials;
  26643. var index;
  26644. for (index = materials.length - 1; index > -1; index--) {
  26645. if (materials[index].id === id) {
  26646. this.material = materials[index];
  26647. return this;
  26648. }
  26649. }
  26650. // Multi
  26651. var multiMaterials = this.getScene().multiMaterials;
  26652. for (index = multiMaterials.length - 1; index > -1; index--) {
  26653. if (multiMaterials[index].id === id) {
  26654. this.material = multiMaterials[index];
  26655. return this;
  26656. }
  26657. }
  26658. return this;
  26659. };
  26660. /**
  26661. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26662. */
  26663. Mesh.prototype.getAnimatables = function () {
  26664. var results = new Array();
  26665. if (this.material) {
  26666. results.push(this.material);
  26667. }
  26668. if (this.skeleton) {
  26669. results.push(this.skeleton);
  26670. }
  26671. return results;
  26672. };
  26673. /**
  26674. * Modifies the mesh geometry according to the passed transformation matrix.
  26675. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26676. * The mesh normals are modified accordingly the same transformation.
  26677. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26678. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26679. * Returns the Mesh.
  26680. */
  26681. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26682. // Position
  26683. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26684. return this;
  26685. }
  26686. var submeshes = this.subMeshes.splice(0);
  26687. this._resetPointsArrayCache();
  26688. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26689. var temp = new Array();
  26690. var index;
  26691. for (index = 0; index < data.length; index += 3) {
  26692. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26693. }
  26694. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26695. // Normals
  26696. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26697. return this;
  26698. }
  26699. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26700. temp = [];
  26701. for (index = 0; index < data.length; index += 3) {
  26702. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26703. }
  26704. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26705. // flip faces?
  26706. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26707. this.flipFaces();
  26708. }
  26709. // Restore submeshes
  26710. this.releaseSubMeshes();
  26711. this.subMeshes = submeshes;
  26712. return this;
  26713. };
  26714. /**
  26715. * Modifies the mesh geometry according to its own current World Matrix.
  26716. * The mesh World Matrix is then reset.
  26717. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26718. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26719. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26720. * Returns the Mesh.
  26721. */
  26722. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26723. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26724. this.scaling.copyFromFloats(1, 1, 1);
  26725. this.position.copyFromFloats(0, 0, 0);
  26726. this.rotation.copyFromFloats(0, 0, 0);
  26727. //only if quaternion is already set
  26728. if (this.rotationQuaternion) {
  26729. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26730. }
  26731. this._worldMatrix = BABYLON.Matrix.Identity();
  26732. return this;
  26733. };
  26734. Object.defineProperty(Mesh.prototype, "_positions", {
  26735. // Cache
  26736. get: function () {
  26737. if (this._geometry) {
  26738. return this._geometry._positions;
  26739. }
  26740. return null;
  26741. },
  26742. enumerable: true,
  26743. configurable: true
  26744. });
  26745. Mesh.prototype._resetPointsArrayCache = function () {
  26746. if (this._geometry) {
  26747. this._geometry._resetPointsArrayCache();
  26748. }
  26749. return this;
  26750. };
  26751. Mesh.prototype._generatePointsArray = function () {
  26752. if (this._geometry) {
  26753. return this._geometry._generatePointsArray();
  26754. }
  26755. return false;
  26756. };
  26757. /**
  26758. * Returns a new Mesh object generated from the current mesh properties.
  26759. * This method must not get confused with createInstance().
  26760. * The parameter `name` is a string, the name given to the new mesh.
  26761. * The optional parameter `newParent` can be any Node object (default `null`).
  26762. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26763. * 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.
  26764. */
  26765. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26766. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26767. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26768. };
  26769. /**
  26770. * Disposes the Mesh.
  26771. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26772. * Returns nothing.
  26773. */
  26774. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26775. var _this = this;
  26776. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26777. this.morphTargetManager = null;
  26778. if (this._geometry) {
  26779. this._geometry.releaseForMesh(this, true);
  26780. }
  26781. // Sources
  26782. var meshes = this.getScene().meshes;
  26783. meshes.forEach(function (abstractMesh) {
  26784. var mesh = abstractMesh;
  26785. if (mesh._source && mesh._source === _this) {
  26786. mesh._source = null;
  26787. }
  26788. });
  26789. this._source = null;
  26790. // Instances
  26791. if (this._instancesBuffer) {
  26792. this._instancesBuffer.dispose();
  26793. this._instancesBuffer = null;
  26794. }
  26795. while (this.instances.length) {
  26796. this.instances[0].dispose();
  26797. }
  26798. // Highlight layers.
  26799. var highlightLayers = this.getScene().highlightLayers;
  26800. for (var i = 0; i < highlightLayers.length; i++) {
  26801. var highlightLayer = highlightLayers[i];
  26802. if (highlightLayer) {
  26803. highlightLayer.removeMesh(this);
  26804. highlightLayer.removeExcludedMesh(this);
  26805. }
  26806. }
  26807. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26808. };
  26809. /**
  26810. * Modifies the mesh geometry according to a displacement map.
  26811. * 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.
  26812. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26813. * This method returns nothing.
  26814. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26815. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26816. * 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.
  26817. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26818. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26819. *
  26820. * Returns the Mesh.
  26821. */
  26822. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26823. var _this = this;
  26824. var scene = this.getScene();
  26825. var onload = function (img) {
  26826. // Getting height map data
  26827. var canvas = document.createElement("canvas");
  26828. var context = canvas.getContext("2d");
  26829. var heightMapWidth = img.width;
  26830. var heightMapHeight = img.height;
  26831. canvas.width = heightMapWidth;
  26832. canvas.height = heightMapHeight;
  26833. context.drawImage(img, 0, 0);
  26834. // Create VertexData from map data
  26835. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26836. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26837. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26838. //execute success callback, if set
  26839. if (onSuccess) {
  26840. onSuccess(_this);
  26841. }
  26842. };
  26843. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26844. return this;
  26845. };
  26846. /**
  26847. * Modifies the mesh geometry according to a displacementMap buffer.
  26848. * 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.
  26849. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26850. * This method returns nothing.
  26851. * 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.
  26852. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26853. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26854. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26855. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26856. *
  26857. * Returns the Mesh.
  26858. */
  26859. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26860. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26861. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26862. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26863. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26864. return this;
  26865. }
  26866. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26867. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26868. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26869. var position = BABYLON.Vector3.Zero();
  26870. var normal = BABYLON.Vector3.Zero();
  26871. var uv = BABYLON.Vector2.Zero();
  26872. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26873. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26874. for (var index = 0; index < positions.length; index += 3) {
  26875. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26876. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26877. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26878. // Compute height
  26879. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26880. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26881. var pos = (u + v * heightMapWidth) * 4;
  26882. var r = buffer[pos] / 255.0;
  26883. var g = buffer[pos + 1] / 255.0;
  26884. var b = buffer[pos + 2] / 255.0;
  26885. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26886. normal.normalize();
  26887. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26888. position = position.add(normal);
  26889. position.toArray(positions, index);
  26890. }
  26891. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26892. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26893. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26894. return this;
  26895. };
  26896. /**
  26897. * Modify the mesh to get a flat shading rendering.
  26898. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26899. * This method returns the Mesh.
  26900. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26901. */
  26902. Mesh.prototype.convertToFlatShadedMesh = function () {
  26903. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26904. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26905. var kinds = this.getVerticesDataKinds();
  26906. var vbs = {};
  26907. var data = {};
  26908. var newdata = {};
  26909. var updatableNormals = false;
  26910. var kindIndex;
  26911. var kind;
  26912. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26913. kind = kinds[kindIndex];
  26914. var vertexBuffer = this.getVertexBuffer(kind);
  26915. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26916. updatableNormals = vertexBuffer.isUpdatable();
  26917. kinds.splice(kindIndex, 1);
  26918. kindIndex--;
  26919. continue;
  26920. }
  26921. vbs[kind] = vertexBuffer;
  26922. data[kind] = vbs[kind].getData();
  26923. newdata[kind] = [];
  26924. }
  26925. // Save previous submeshes
  26926. var previousSubmeshes = this.subMeshes.slice(0);
  26927. var indices = this.getIndices();
  26928. var totalIndices = this.getTotalIndices();
  26929. // Generating unique vertices per face
  26930. var index;
  26931. for (index = 0; index < totalIndices; index++) {
  26932. var vertexIndex = indices[index];
  26933. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26934. kind = kinds[kindIndex];
  26935. var stride = vbs[kind].getStrideSize();
  26936. for (var offset = 0; offset < stride; offset++) {
  26937. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26938. }
  26939. }
  26940. }
  26941. // Updating faces & normal
  26942. var normals = [];
  26943. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26944. for (index = 0; index < totalIndices; index += 3) {
  26945. indices[index] = index;
  26946. indices[index + 1] = index + 1;
  26947. indices[index + 2] = index + 2;
  26948. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26949. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26950. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26951. var p1p2 = p1.subtract(p2);
  26952. var p3p2 = p3.subtract(p2);
  26953. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26954. // Store same normals for every vertex
  26955. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26956. normals.push(normal.x);
  26957. normals.push(normal.y);
  26958. normals.push(normal.z);
  26959. }
  26960. }
  26961. this.setIndices(indices);
  26962. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26963. // Updating vertex buffers
  26964. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26965. kind = kinds[kindIndex];
  26966. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26967. }
  26968. // Updating submeshes
  26969. this.releaseSubMeshes();
  26970. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26971. var previousOne = previousSubmeshes[submeshIndex];
  26972. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26973. }
  26974. this.synchronizeInstances();
  26975. return this;
  26976. };
  26977. /**
  26978. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26979. * In other words, more vertices, no more indices and a single bigger VBO.
  26980. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26981. * Returns the Mesh.
  26982. */
  26983. Mesh.prototype.convertToUnIndexedMesh = function () {
  26984. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26985. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26986. var kinds = this.getVerticesDataKinds();
  26987. var vbs = {};
  26988. var data = {};
  26989. var newdata = {};
  26990. var kindIndex;
  26991. var kind;
  26992. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26993. kind = kinds[kindIndex];
  26994. var vertexBuffer = this.getVertexBuffer(kind);
  26995. vbs[kind] = vertexBuffer;
  26996. data[kind] = vbs[kind].getData();
  26997. newdata[kind] = [];
  26998. }
  26999. // Save previous submeshes
  27000. var previousSubmeshes = this.subMeshes.slice(0);
  27001. var indices = this.getIndices();
  27002. var totalIndices = this.getTotalIndices();
  27003. // Generating unique vertices per face
  27004. var index;
  27005. for (index = 0; index < totalIndices; index++) {
  27006. var vertexIndex = indices[index];
  27007. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27008. kind = kinds[kindIndex];
  27009. var stride = vbs[kind].getStrideSize();
  27010. for (var offset = 0; offset < stride; offset++) {
  27011. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27012. }
  27013. }
  27014. }
  27015. // Updating indices
  27016. for (index = 0; index < totalIndices; index += 3) {
  27017. indices[index] = index;
  27018. indices[index + 1] = index + 1;
  27019. indices[index + 2] = index + 2;
  27020. }
  27021. this.setIndices(indices);
  27022. // Updating vertex buffers
  27023. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27024. kind = kinds[kindIndex];
  27025. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27026. }
  27027. // Updating submeshes
  27028. this.releaseSubMeshes();
  27029. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27030. var previousOne = previousSubmeshes[submeshIndex];
  27031. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27032. }
  27033. this._unIndexed = true;
  27034. this.synchronizeInstances();
  27035. return this;
  27036. };
  27037. /**
  27038. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27039. * This method returns the Mesh.
  27040. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27041. */
  27042. Mesh.prototype.flipFaces = function (flipNormals) {
  27043. if (flipNormals === void 0) { flipNormals = false; }
  27044. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27045. var i;
  27046. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27047. for (i = 0; i < vertex_data.normals.length; i++) {
  27048. vertex_data.normals[i] *= -1;
  27049. }
  27050. }
  27051. if (vertex_data.indices) {
  27052. var temp;
  27053. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27054. // reassign indices
  27055. temp = vertex_data.indices[i + 1];
  27056. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27057. vertex_data.indices[i + 2] = temp;
  27058. }
  27059. }
  27060. vertex_data.applyToMesh(this);
  27061. return this;
  27062. };
  27063. // Instances
  27064. /**
  27065. * Creates a new InstancedMesh object from the mesh model.
  27066. * An instance shares the same properties and the same material than its model.
  27067. * Only these properties of each instance can then be set individually :
  27068. * - position
  27069. * - rotation
  27070. * - rotationQuaternion
  27071. * - setPivotMatrix
  27072. * - scaling
  27073. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27074. * Warning : this method is not supported for Line mesh and LineSystem
  27075. */
  27076. Mesh.prototype.createInstance = function (name) {
  27077. return new BABYLON.InstancedMesh(name, this);
  27078. };
  27079. /**
  27080. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27081. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27082. * This method returns the Mesh.
  27083. */
  27084. Mesh.prototype.synchronizeInstances = function () {
  27085. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27086. var instance = this.instances[instanceIndex];
  27087. instance._syncSubMeshes();
  27088. }
  27089. return this;
  27090. };
  27091. /**
  27092. * Simplify the mesh according to the given array of settings.
  27093. * Function will return immediately and will simplify async. It returns the Mesh.
  27094. * @param settings a collection of simplification settings.
  27095. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27096. * @param type the type of simplification to run.
  27097. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27098. */
  27099. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27100. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27101. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27102. this.getScene().simplificationQueue.addTask({
  27103. settings: settings,
  27104. parallelProcessing: parallelProcessing,
  27105. mesh: this,
  27106. simplificationType: simplificationType,
  27107. successCallback: successCallback
  27108. });
  27109. return this;
  27110. };
  27111. /**
  27112. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27113. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27114. * This should be used together with the simplification to avoid disappearing triangles.
  27115. * Returns the Mesh.
  27116. * @param successCallback an optional success callback to be called after the optimization finished.
  27117. */
  27118. Mesh.prototype.optimizeIndices = function (successCallback) {
  27119. var _this = this;
  27120. var indices = this.getIndices();
  27121. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27122. if (!positions || !indices) {
  27123. return this;
  27124. }
  27125. var vectorPositions = new Array();
  27126. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27127. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27128. }
  27129. var dupes = new Array();
  27130. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27131. var realPos = vectorPositions.length - 1 - iteration;
  27132. var testedPosition = vectorPositions[realPos];
  27133. for (var j = 0; j < realPos; ++j) {
  27134. var againstPosition = vectorPositions[j];
  27135. if (testedPosition.equals(againstPosition)) {
  27136. dupes[realPos] = j;
  27137. break;
  27138. }
  27139. }
  27140. }, function () {
  27141. for (var i = 0; i < indices.length; ++i) {
  27142. indices[i] = dupes[indices[i]] || indices[i];
  27143. }
  27144. //indices are now reordered
  27145. var originalSubMeshes = _this.subMeshes.slice(0);
  27146. _this.setIndices(indices);
  27147. _this.subMeshes = originalSubMeshes;
  27148. if (successCallback) {
  27149. successCallback(_this);
  27150. }
  27151. });
  27152. return this;
  27153. };
  27154. Mesh.prototype.serialize = function (serializationObject) {
  27155. serializationObject.name = this.name;
  27156. serializationObject.id = this.id;
  27157. serializationObject.type = this.getClassName();
  27158. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27159. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27160. }
  27161. serializationObject.position = this.position.asArray();
  27162. if (this.rotationQuaternion) {
  27163. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27164. }
  27165. else if (this.rotation) {
  27166. serializationObject.rotation = this.rotation.asArray();
  27167. }
  27168. serializationObject.scaling = this.scaling.asArray();
  27169. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27170. serializationObject.isEnabled = this.isEnabled(false);
  27171. serializationObject.isVisible = this.isVisible;
  27172. serializationObject.infiniteDistance = this.infiniteDistance;
  27173. serializationObject.pickable = this.isPickable;
  27174. serializationObject.receiveShadows = this.receiveShadows;
  27175. serializationObject.billboardMode = this.billboardMode;
  27176. serializationObject.visibility = this.visibility;
  27177. serializationObject.checkCollisions = this.checkCollisions;
  27178. serializationObject.isBlocker = this.isBlocker;
  27179. // Parent
  27180. if (this.parent) {
  27181. serializationObject.parentId = this.parent.id;
  27182. }
  27183. // Geometry
  27184. serializationObject.isUnIndexed = this.isUnIndexed;
  27185. var geometry = this._geometry;
  27186. if (geometry) {
  27187. var geometryId = geometry.id;
  27188. serializationObject.geometryId = geometryId;
  27189. // SubMeshes
  27190. serializationObject.subMeshes = [];
  27191. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27192. var subMesh = this.subMeshes[subIndex];
  27193. serializationObject.subMeshes.push({
  27194. materialIndex: subMesh.materialIndex,
  27195. verticesStart: subMesh.verticesStart,
  27196. verticesCount: subMesh.verticesCount,
  27197. indexStart: subMesh.indexStart,
  27198. indexCount: subMesh.indexCount
  27199. });
  27200. }
  27201. }
  27202. // Material
  27203. if (this.material) {
  27204. serializationObject.materialId = this.material.id;
  27205. }
  27206. else {
  27207. this.material = null;
  27208. }
  27209. // Morph targets
  27210. if (this.morphTargetManager) {
  27211. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27212. }
  27213. // Skeleton
  27214. if (this.skeleton) {
  27215. serializationObject.skeletonId = this.skeleton.id;
  27216. }
  27217. // Physics
  27218. //TODO implement correct serialization for physics impostors.
  27219. var impostor = this.getPhysicsImpostor();
  27220. if (impostor) {
  27221. serializationObject.physicsMass = impostor.getParam("mass");
  27222. serializationObject.physicsFriction = impostor.getParam("friction");
  27223. serializationObject.physicsRestitution = impostor.getParam("mass");
  27224. serializationObject.physicsImpostor = impostor.type;
  27225. }
  27226. // Metadata
  27227. if (this.metadata) {
  27228. serializationObject.metadata = this.metadata;
  27229. }
  27230. // Instances
  27231. serializationObject.instances = [];
  27232. for (var index = 0; index < this.instances.length; index++) {
  27233. var instance = this.instances[index];
  27234. var serializationInstance = {
  27235. name: instance.name,
  27236. id: instance.id,
  27237. position: instance.position.asArray(),
  27238. scaling: instance.scaling.asArray()
  27239. };
  27240. if (instance.rotationQuaternion) {
  27241. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27242. }
  27243. else if (instance.rotation) {
  27244. serializationInstance.rotation = instance.rotation.asArray();
  27245. }
  27246. serializationObject.instances.push(serializationInstance);
  27247. // Animations
  27248. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27249. serializationInstance.ranges = instance.serializeAnimationRanges();
  27250. }
  27251. //
  27252. // Animations
  27253. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27254. serializationObject.ranges = this.serializeAnimationRanges();
  27255. // Layer mask
  27256. serializationObject.layerMask = this.layerMask;
  27257. // Alpha
  27258. serializationObject.alphaIndex = this.alphaIndex;
  27259. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27260. // Overlay
  27261. serializationObject.overlayAlpha = this.overlayAlpha;
  27262. serializationObject.overlayColor = this.overlayColor.asArray();
  27263. serializationObject.renderOverlay = this.renderOverlay;
  27264. // Fog
  27265. serializationObject.applyFog = this.applyFog;
  27266. // Action Manager
  27267. if (this.actionManager) {
  27268. serializationObject.actions = this.actionManager.serialize(this.name);
  27269. }
  27270. };
  27271. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27272. if (!this.geometry) {
  27273. return;
  27274. }
  27275. this._markSubMeshesAsAttributesDirty();
  27276. var morphTargetManager = this._morphTargetManager;
  27277. if (morphTargetManager && morphTargetManager.vertexCount) {
  27278. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27279. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27280. this.morphTargetManager = null;
  27281. return;
  27282. }
  27283. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27284. var morphTarget = morphTargetManager.getActiveTarget(index);
  27285. var positions = morphTarget.getPositions();
  27286. if (!positions) {
  27287. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27288. return;
  27289. }
  27290. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27291. var normals = morphTarget.getNormals();
  27292. if (normals) {
  27293. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27294. }
  27295. var tangents = morphTarget.getTangents();
  27296. if (tangents) {
  27297. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27298. }
  27299. }
  27300. }
  27301. else {
  27302. var index = 0;
  27303. // Positions
  27304. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27305. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27306. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27307. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27308. }
  27309. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27310. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27311. }
  27312. index++;
  27313. }
  27314. }
  27315. };
  27316. // Statics
  27317. /**
  27318. * Returns a new Mesh object parsed from the source provided.
  27319. * The parameter `parsedMesh` is the source.
  27320. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27321. */
  27322. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27323. var mesh;
  27324. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27325. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27326. }
  27327. else {
  27328. mesh = new Mesh(parsedMesh.name, scene);
  27329. }
  27330. mesh.id = parsedMesh.id;
  27331. if (BABYLON.Tags) {
  27332. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27333. }
  27334. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27335. if (parsedMesh.metadata !== undefined) {
  27336. mesh.metadata = parsedMesh.metadata;
  27337. }
  27338. if (parsedMesh.rotationQuaternion) {
  27339. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27340. }
  27341. else if (parsedMesh.rotation) {
  27342. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27343. }
  27344. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27345. if (parsedMesh.localMatrix) {
  27346. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27347. }
  27348. else if (parsedMesh.pivotMatrix) {
  27349. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27350. }
  27351. mesh.setEnabled(parsedMesh.isEnabled);
  27352. mesh.isVisible = parsedMesh.isVisible;
  27353. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27354. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27355. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27356. if (parsedMesh.applyFog !== undefined) {
  27357. mesh.applyFog = parsedMesh.applyFog;
  27358. }
  27359. if (parsedMesh.pickable !== undefined) {
  27360. mesh.isPickable = parsedMesh.pickable;
  27361. }
  27362. if (parsedMesh.alphaIndex !== undefined) {
  27363. mesh.alphaIndex = parsedMesh.alphaIndex;
  27364. }
  27365. mesh.receiveShadows = parsedMesh.receiveShadows;
  27366. mesh.billboardMode = parsedMesh.billboardMode;
  27367. if (parsedMesh.visibility !== undefined) {
  27368. mesh.visibility = parsedMesh.visibility;
  27369. }
  27370. mesh.checkCollisions = parsedMesh.checkCollisions;
  27371. if (parsedMesh.isBlocker !== undefined) {
  27372. mesh.isBlocker = parsedMesh.isBlocker;
  27373. }
  27374. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27375. // freezeWorldMatrix
  27376. if (parsedMesh.freezeWorldMatrix) {
  27377. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27378. }
  27379. // Parent
  27380. if (parsedMesh.parentId) {
  27381. mesh._waitingParentId = parsedMesh.parentId;
  27382. }
  27383. // Actions
  27384. if (parsedMesh.actions !== undefined) {
  27385. mesh._waitingActions = parsedMesh.actions;
  27386. }
  27387. // Overlay
  27388. if (parsedMesh.overlayAlpha !== undefined) {
  27389. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27390. }
  27391. if (parsedMesh.overlayColor !== undefined) {
  27392. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27393. }
  27394. if (parsedMesh.renderOverlay !== undefined) {
  27395. mesh.renderOverlay = parsedMesh.renderOverlay;
  27396. }
  27397. // Geometry
  27398. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27399. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27400. if (parsedMesh.delayLoadingFile) {
  27401. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27402. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27403. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27404. if (parsedMesh._binaryInfo) {
  27405. mesh._binaryInfo = parsedMesh._binaryInfo;
  27406. }
  27407. mesh._delayInfo = [];
  27408. if (parsedMesh.hasUVs) {
  27409. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27410. }
  27411. if (parsedMesh.hasUVs2) {
  27412. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27413. }
  27414. if (parsedMesh.hasUVs3) {
  27415. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27416. }
  27417. if (parsedMesh.hasUVs4) {
  27418. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27419. }
  27420. if (parsedMesh.hasUVs5) {
  27421. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27422. }
  27423. if (parsedMesh.hasUVs6) {
  27424. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27425. }
  27426. if (parsedMesh.hasColors) {
  27427. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27428. }
  27429. if (parsedMesh.hasMatricesIndices) {
  27430. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27431. }
  27432. if (parsedMesh.hasMatricesWeights) {
  27433. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27434. }
  27435. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27436. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27437. mesh._checkDelayState();
  27438. }
  27439. }
  27440. else {
  27441. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27442. }
  27443. // Material
  27444. if (parsedMesh.materialId) {
  27445. mesh.setMaterialByID(parsedMesh.materialId);
  27446. }
  27447. else {
  27448. mesh.material = null;
  27449. }
  27450. // Morph targets
  27451. if (parsedMesh.morphTargetManagerId > -1) {
  27452. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27453. }
  27454. // Skeleton
  27455. if (parsedMesh.skeletonId > -1) {
  27456. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27457. if (parsedMesh.numBoneInfluencers) {
  27458. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27459. }
  27460. }
  27461. // Animations
  27462. if (parsedMesh.animations) {
  27463. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27464. var parsedAnimation = parsedMesh.animations[animationIndex];
  27465. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27466. }
  27467. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27468. }
  27469. if (parsedMesh.autoAnimate) {
  27470. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27471. }
  27472. // Layer Mask
  27473. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27474. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27475. }
  27476. else {
  27477. mesh.layerMask = 0x0FFFFFFF;
  27478. }
  27479. // Physics
  27480. if (parsedMesh.physicsImpostor) {
  27481. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27482. mass: parsedMesh.physicsMass,
  27483. friction: parsedMesh.physicsFriction,
  27484. restitution: parsedMesh.physicsRestitution
  27485. }, scene);
  27486. }
  27487. // Instances
  27488. if (parsedMesh.instances) {
  27489. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27490. var parsedInstance = parsedMesh.instances[index];
  27491. var instance = mesh.createInstance(parsedInstance.name);
  27492. if (parsedInstance.id) {
  27493. instance.id = parsedInstance.id;
  27494. }
  27495. if (BABYLON.Tags) {
  27496. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27497. }
  27498. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27499. if (parsedInstance.parentId) {
  27500. instance._waitingParentId = parsedInstance.parentId;
  27501. }
  27502. if (parsedInstance.rotationQuaternion) {
  27503. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27504. }
  27505. else if (parsedInstance.rotation) {
  27506. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27507. }
  27508. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27509. instance.checkCollisions = mesh.checkCollisions;
  27510. if (parsedMesh.animations) {
  27511. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27512. parsedAnimation = parsedMesh.animations[animationIndex];
  27513. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27514. }
  27515. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27516. }
  27517. }
  27518. }
  27519. return mesh;
  27520. };
  27521. /**
  27522. * Creates a ribbon mesh.
  27523. * Please consider using the same method from the MeshBuilder class instead.
  27524. * 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.
  27525. *
  27526. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27527. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27528. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27529. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27530. * 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.
  27531. * 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.
  27532. * 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
  27533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27536. */
  27537. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27538. if (closeArray === void 0) { closeArray = false; }
  27539. if (updatable === void 0) { updatable = false; }
  27540. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27541. pathArray: pathArray,
  27542. closeArray: closeArray,
  27543. closePath: closePath,
  27544. offset: offset,
  27545. updatable: updatable,
  27546. sideOrientation: sideOrientation,
  27547. instance: instance
  27548. }, scene);
  27549. };
  27550. /**
  27551. * Creates a plane polygonal mesh. By default, this is a disc.
  27552. * Please consider using the same method from the MeshBuilder class instead.
  27553. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27554. * 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.
  27555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27558. */
  27559. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27560. if (scene === void 0) { scene = null; }
  27561. var options = {
  27562. radius: radius,
  27563. tessellation: tessellation,
  27564. sideOrientation: sideOrientation,
  27565. updatable: updatable
  27566. };
  27567. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27568. };
  27569. /**
  27570. * Creates a box mesh.
  27571. * Please consider using the same method from the MeshBuilder class instead.
  27572. * The parameter `size` sets the size (float) of each box side (default 1).
  27573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27576. */
  27577. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27578. if (scene === void 0) { scene = null; }
  27579. var options = {
  27580. size: size,
  27581. sideOrientation: sideOrientation,
  27582. updatable: updatable
  27583. };
  27584. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27585. };
  27586. /**
  27587. * Creates a sphere mesh.
  27588. * Please consider using the same method from the MeshBuilder class instead.
  27589. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27590. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27594. */
  27595. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27596. var options = {
  27597. segments: segments,
  27598. diameterX: diameter,
  27599. diameterY: diameter,
  27600. diameterZ: diameter,
  27601. sideOrientation: sideOrientation,
  27602. updatable: updatable
  27603. };
  27604. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27605. };
  27606. /**
  27607. * Creates a cylinder or a cone mesh.
  27608. * Please consider using the same method from the MeshBuilder class instead.
  27609. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27610. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27611. * 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.
  27612. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27613. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27614. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27615. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27616. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27617. */
  27618. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27619. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27620. if (scene !== undefined) {
  27621. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27622. updatable = scene;
  27623. }
  27624. scene = subdivisions;
  27625. subdivisions = 1;
  27626. }
  27627. var options = {
  27628. height: height,
  27629. diameterTop: diameterTop,
  27630. diameterBottom: diameterBottom,
  27631. tessellation: tessellation,
  27632. subdivisions: subdivisions,
  27633. sideOrientation: sideOrientation,
  27634. updatable: updatable
  27635. };
  27636. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27637. };
  27638. // Torus (Code from SharpDX.org)
  27639. /**
  27640. * Creates a torus mesh.
  27641. * Please consider using the same method from the MeshBuilder class instead.
  27642. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27643. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27644. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27645. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27648. */
  27649. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27650. var options = {
  27651. diameter: diameter,
  27652. thickness: thickness,
  27653. tessellation: tessellation,
  27654. sideOrientation: sideOrientation,
  27655. updatable: updatable
  27656. };
  27657. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27658. };
  27659. /**
  27660. * Creates a torus knot mesh.
  27661. * Please consider using the same method from the MeshBuilder class instead.
  27662. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27663. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27664. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27665. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27669. */
  27670. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27671. var options = {
  27672. radius: radius,
  27673. tube: tube,
  27674. radialSegments: radialSegments,
  27675. tubularSegments: tubularSegments,
  27676. p: p,
  27677. q: q,
  27678. sideOrientation: sideOrientation,
  27679. updatable: updatable
  27680. };
  27681. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27682. };
  27683. /**
  27684. * Creates a line mesh.
  27685. * Please consider using the same method from the MeshBuilder class instead.
  27686. * 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.
  27687. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27688. * The parameter `points` is an array successive Vector3.
  27689. * 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
  27690. * When updating an instance, remember that only point positions can change, not the number of points.
  27691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27692. */
  27693. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27694. if (scene === void 0) { scene = null; }
  27695. if (updatable === void 0) { updatable = false; }
  27696. if (instance === void 0) { instance = null; }
  27697. var options = {
  27698. points: points,
  27699. updatable: updatable,
  27700. instance: instance
  27701. };
  27702. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27703. };
  27704. /**
  27705. * Creates a dashed line mesh.
  27706. * Please consider using the same method from the MeshBuilder class instead.
  27707. * 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.
  27708. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27709. * The parameter `points` is an array successive Vector3.
  27710. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27711. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27712. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27713. * 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
  27714. * When updating an instance, remember that only point positions can change, not the number of points.
  27715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27716. */
  27717. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27718. if (scene === void 0) { scene = null; }
  27719. var options = {
  27720. points: points,
  27721. dashSize: dashSize,
  27722. gapSize: gapSize,
  27723. dashNb: dashNb,
  27724. updatable: updatable,
  27725. instance: instance
  27726. };
  27727. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27728. };
  27729. /**
  27730. * Creates a polygon mesh.
  27731. * Please consider using the same method from the MeshBuilder class instead.
  27732. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27733. * 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.
  27734. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27736. * Remember you can only change the shape positions, not their number when updating a polygon.
  27737. */
  27738. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27739. var options = {
  27740. shape: shape,
  27741. holes: holes,
  27742. updatable: updatable,
  27743. sideOrientation: sideOrientation
  27744. };
  27745. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27746. };
  27747. /**
  27748. * Creates an extruded polygon mesh, with depth in the Y direction.
  27749. * Please consider using the same method from the MeshBuilder class instead.
  27750. */
  27751. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27752. var options = {
  27753. shape: shape,
  27754. holes: holes,
  27755. depth: depth,
  27756. updatable: updatable,
  27757. sideOrientation: sideOrientation
  27758. };
  27759. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27760. };
  27761. /**
  27762. * Creates an extruded shape mesh.
  27763. * 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.
  27764. * Please consider using the same method from the MeshBuilder class instead.
  27765. *
  27766. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27767. * 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
  27768. * extruded along the Z axis.
  27769. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27770. * 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.
  27771. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27772. * 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
  27773. * 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
  27774. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27775. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27778. */
  27779. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27780. if (scene === void 0) { scene = null; }
  27781. var options = {
  27782. shape: shape,
  27783. path: path,
  27784. scale: scale,
  27785. rotation: rotation,
  27786. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27787. sideOrientation: sideOrientation,
  27788. instance: instance,
  27789. updatable: updatable
  27790. };
  27791. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27792. };
  27793. /**
  27794. * Creates an custom extruded shape mesh.
  27795. * 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.
  27796. * Please consider using the same method from the MeshBuilder class instead.
  27797. *
  27798. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27799. * 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
  27800. * extruded along the Z axis.
  27801. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27802. * 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
  27803. * and the distance of this point from the begining of the path :
  27804. * ```javascript
  27805. * var rotationFunction = function(i, distance) {
  27806. * // do things
  27807. * return rotationValue; }
  27808. * ```
  27809. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27810. * 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
  27811. * and the distance of this point from the begining of the path :
  27812. * ```javascript
  27813. * var scaleFunction = function(i, distance) {
  27814. * // do things
  27815. * return scaleValue;}
  27816. * ```
  27817. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27818. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27819. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27820. * 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
  27821. * 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
  27822. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27823. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27824. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27826. */
  27827. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27828. var options = {
  27829. shape: shape,
  27830. path: path,
  27831. scaleFunction: scaleFunction,
  27832. rotationFunction: rotationFunction,
  27833. ribbonCloseArray: ribbonCloseArray,
  27834. ribbonClosePath: ribbonClosePath,
  27835. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27836. sideOrientation: sideOrientation,
  27837. instance: instance,
  27838. updatable: updatable
  27839. };
  27840. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27841. };
  27842. /**
  27843. * Creates lathe mesh.
  27844. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27845. * Please consider using the same method from the MeshBuilder class instead.
  27846. * 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
  27847. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27848. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27849. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27853. */
  27854. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27855. var options = {
  27856. shape: shape,
  27857. radius: radius,
  27858. tessellation: tessellation,
  27859. sideOrientation: sideOrientation,
  27860. updatable: updatable
  27861. };
  27862. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27863. };
  27864. /**
  27865. * Creates a plane mesh.
  27866. * Please consider using the same method from the MeshBuilder class instead.
  27867. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27868. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27869. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27871. */
  27872. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27873. var options = {
  27874. size: size,
  27875. width: size,
  27876. height: size,
  27877. sideOrientation: sideOrientation,
  27878. updatable: updatable
  27879. };
  27880. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27881. };
  27882. /**
  27883. * Creates a ground mesh.
  27884. * Please consider using the same method from the MeshBuilder class instead.
  27885. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27886. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27888. */
  27889. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27890. var options = {
  27891. width: width,
  27892. height: height,
  27893. subdivisions: subdivisions,
  27894. updatable: updatable
  27895. };
  27896. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27897. };
  27898. /**
  27899. * Creates a tiled ground mesh.
  27900. * Please consider using the same method from the MeshBuilder class instead.
  27901. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27902. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27903. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27904. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27905. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27906. * numbers of subdivisions on the ground width and height of each tile.
  27907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27908. */
  27909. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27910. var options = {
  27911. xmin: xmin,
  27912. zmin: zmin,
  27913. xmax: xmax,
  27914. zmax: zmax,
  27915. subdivisions: subdivisions,
  27916. precision: precision,
  27917. updatable: updatable
  27918. };
  27919. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27920. };
  27921. /**
  27922. * Creates a ground mesh from a height map.
  27923. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27924. * Please consider using the same method from the MeshBuilder class instead.
  27925. * The parameter `url` sets the URL of the height map image resource.
  27926. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27927. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27928. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27929. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27930. * 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).
  27931. * This function is passed the newly built mesh :
  27932. * ```javascript
  27933. * function(mesh) { // do things
  27934. * return; }
  27935. * ```
  27936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27937. */
  27938. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27939. var options = {
  27940. width: width,
  27941. height: height,
  27942. subdivisions: subdivisions,
  27943. minHeight: minHeight,
  27944. maxHeight: maxHeight,
  27945. updatable: updatable,
  27946. onReady: onReady
  27947. };
  27948. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27949. };
  27950. /**
  27951. * Creates a tube mesh.
  27952. * 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.
  27953. * Please consider using the same method from the MeshBuilder class instead.
  27954. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27955. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27956. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27957. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27958. * 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.
  27959. * It must return a radius value (positive float) :
  27960. * ```javascript
  27961. * var radiusFunction = function(i, distance) {
  27962. * // do things
  27963. * return radius; }
  27964. * ```
  27965. * 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
  27966. * 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
  27967. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27968. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27970. */
  27971. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27972. var options = {
  27973. path: path,
  27974. radius: radius,
  27975. tessellation: tessellation,
  27976. radiusFunction: radiusFunction,
  27977. arc: 1,
  27978. cap: cap,
  27979. updatable: updatable,
  27980. sideOrientation: sideOrientation,
  27981. instance: instance
  27982. };
  27983. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27984. };
  27985. /**
  27986. * Creates a polyhedron mesh.
  27987. * Please consider using the same method from the MeshBuilder class instead.
  27988. * 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
  27989. * to choose the wanted type.
  27990. * The parameter `size` (positive float, default 1) sets the polygon size.
  27991. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27992. * 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`.
  27993. * 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
  27994. * 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)`).
  27995. * 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
  27996. * 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.
  27997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27998. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28000. */
  28001. Mesh.CreatePolyhedron = function (name, options, scene) {
  28002. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28003. };
  28004. /**
  28005. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28006. * Please consider using the same method from the MeshBuilder class instead.
  28007. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28008. * 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`).
  28009. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28010. * 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.
  28011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28012. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28014. */
  28015. Mesh.CreateIcoSphere = function (name, options, scene) {
  28016. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28017. };
  28018. /**
  28019. * Creates a decal mesh.
  28020. * Please consider using the same method from the MeshBuilder class instead.
  28021. * 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.
  28022. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28023. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28024. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28025. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28026. */
  28027. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28028. var options = {
  28029. position: position,
  28030. normal: normal,
  28031. size: size,
  28032. angle: angle
  28033. };
  28034. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28035. };
  28036. // Skeletons
  28037. /**
  28038. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28039. */
  28040. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28041. if (!this._sourcePositions) {
  28042. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28043. if (!source) {
  28044. return this._sourcePositions;
  28045. }
  28046. this._sourcePositions = new Float32Array(source);
  28047. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28048. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28049. }
  28050. }
  28051. return this._sourcePositions;
  28052. };
  28053. /**
  28054. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28055. */
  28056. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28057. if (!this._sourceNormals) {
  28058. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28059. if (!source) {
  28060. return this._sourceNormals;
  28061. }
  28062. this._sourceNormals = new Float32Array(source);
  28063. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28064. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28065. }
  28066. }
  28067. return this._sourceNormals;
  28068. };
  28069. /**
  28070. * Updates the vertex buffer by applying transformation from the bones.
  28071. * Returns the Mesh.
  28072. *
  28073. * @param {skeleton} skeleton to apply
  28074. */
  28075. Mesh.prototype.applySkeleton = function (skeleton) {
  28076. if (!this.geometry) {
  28077. return this;
  28078. }
  28079. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28080. return this;
  28081. }
  28082. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28083. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28084. return this;
  28085. }
  28086. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28087. return this;
  28088. }
  28089. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28090. return this;
  28091. }
  28092. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28093. return this;
  28094. }
  28095. if (!this._sourcePositions) {
  28096. var submeshes = this.subMeshes.slice();
  28097. this.setPositionsForCPUSkinning();
  28098. this.subMeshes = submeshes;
  28099. }
  28100. if (!this._sourceNormals) {
  28101. this.setNormalsForCPUSkinning();
  28102. }
  28103. // positionsData checks for not being Float32Array will only pass at most once
  28104. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28105. if (!positionsData) {
  28106. return this;
  28107. }
  28108. if (!(positionsData instanceof Float32Array)) {
  28109. positionsData = new Float32Array(positionsData);
  28110. }
  28111. // normalsData checks for not being Float32Array will only pass at most once
  28112. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28113. if (!normalsData) {
  28114. return this;
  28115. }
  28116. if (!(normalsData instanceof Float32Array)) {
  28117. normalsData = new Float32Array(normalsData);
  28118. }
  28119. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28120. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28121. if (!matricesWeightsData || !matricesIndicesData) {
  28122. return this;
  28123. }
  28124. var needExtras = this.numBoneInfluencers > 4;
  28125. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28126. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28127. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28128. var tempVector3 = BABYLON.Vector3.Zero();
  28129. var finalMatrix = new BABYLON.Matrix();
  28130. var tempMatrix = new BABYLON.Matrix();
  28131. var matWeightIdx = 0;
  28132. var inf;
  28133. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28134. var weight;
  28135. for (inf = 0; inf < 4; inf++) {
  28136. weight = matricesWeightsData[matWeightIdx + inf];
  28137. if (weight > 0) {
  28138. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28139. finalMatrix.addToSelf(tempMatrix);
  28140. }
  28141. else
  28142. break;
  28143. }
  28144. if (needExtras) {
  28145. for (inf = 0; inf < 4; inf++) {
  28146. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28147. if (weight > 0) {
  28148. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28149. finalMatrix.addToSelf(tempMatrix);
  28150. }
  28151. else
  28152. break;
  28153. }
  28154. }
  28155. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28156. tempVector3.toArray(positionsData, index);
  28157. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28158. tempVector3.toArray(normalsData, index);
  28159. finalMatrix.reset();
  28160. }
  28161. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28162. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28163. return this;
  28164. };
  28165. // Tools
  28166. /**
  28167. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28168. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28169. */
  28170. Mesh.MinMax = function (meshes) {
  28171. var minVector = null;
  28172. var maxVector = null;
  28173. meshes.forEach(function (mesh, index, array) {
  28174. var boundingInfo = mesh.getBoundingInfo();
  28175. var boundingBox = boundingInfo.boundingBox;
  28176. if (!minVector || !maxVector) {
  28177. minVector = boundingBox.minimumWorld;
  28178. maxVector = boundingBox.maximumWorld;
  28179. }
  28180. else {
  28181. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28182. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28183. }
  28184. });
  28185. if (!minVector || !maxVector) {
  28186. return {
  28187. min: BABYLON.Vector3.Zero(),
  28188. max: BABYLON.Vector3.Zero()
  28189. };
  28190. }
  28191. return {
  28192. min: minVector,
  28193. max: maxVector
  28194. };
  28195. };
  28196. /**
  28197. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28198. */
  28199. Mesh.Center = function (meshesOrMinMaxVector) {
  28200. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28201. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28202. };
  28203. /**
  28204. * Merge the array of meshes into a single mesh for performance reasons.
  28205. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28206. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28207. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28208. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28209. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28210. */
  28211. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28212. if (disposeSource === void 0) { disposeSource = true; }
  28213. var index;
  28214. if (!allow32BitsIndices) {
  28215. var totalVertices = 0;
  28216. // Counting vertices
  28217. for (index = 0; index < meshes.length; index++) {
  28218. if (meshes[index]) {
  28219. totalVertices += meshes[index].getTotalVertices();
  28220. if (totalVertices > 65536) {
  28221. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28222. return null;
  28223. }
  28224. }
  28225. }
  28226. }
  28227. // Merge
  28228. var vertexData = null;
  28229. var otherVertexData;
  28230. var indiceArray = new Array();
  28231. var source = null;
  28232. for (index = 0; index < meshes.length; index++) {
  28233. if (meshes[index]) {
  28234. meshes[index].computeWorldMatrix(true);
  28235. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28236. otherVertexData.transform(meshes[index].getWorldMatrix());
  28237. if (vertexData) {
  28238. vertexData.merge(otherVertexData);
  28239. }
  28240. else {
  28241. vertexData = otherVertexData;
  28242. source = meshes[index];
  28243. }
  28244. if (subdivideWithSubMeshes) {
  28245. indiceArray.push(meshes[index].getTotalIndices());
  28246. }
  28247. }
  28248. }
  28249. source = source;
  28250. if (!meshSubclass) {
  28251. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28252. }
  28253. vertexData.applyToMesh(meshSubclass);
  28254. // Setting properties
  28255. meshSubclass.material = source.material;
  28256. meshSubclass.checkCollisions = source.checkCollisions;
  28257. // Cleaning
  28258. if (disposeSource) {
  28259. for (index = 0; index < meshes.length; index++) {
  28260. if (meshes[index]) {
  28261. meshes[index].dispose();
  28262. }
  28263. }
  28264. }
  28265. // Subdivide
  28266. if (subdivideWithSubMeshes) {
  28267. //-- Suppresions du submesh global
  28268. meshSubclass.releaseSubMeshes();
  28269. index = 0;
  28270. var offset = 0;
  28271. //-- aplique la subdivision en fonction du tableau d'indices
  28272. while (index < indiceArray.length) {
  28273. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28274. offset += indiceArray[index];
  28275. index++;
  28276. }
  28277. }
  28278. return meshSubclass;
  28279. };
  28280. // Consts
  28281. Mesh._FRONTSIDE = 0;
  28282. Mesh._BACKSIDE = 1;
  28283. Mesh._DOUBLESIDE = 2;
  28284. Mesh._DEFAULTSIDE = 0;
  28285. Mesh._NO_CAP = 0;
  28286. Mesh._CAP_START = 1;
  28287. Mesh._CAP_END = 2;
  28288. Mesh._CAP_ALL = 3;
  28289. return Mesh;
  28290. }(BABYLON.AbstractMesh));
  28291. BABYLON.Mesh = Mesh;
  28292. })(BABYLON || (BABYLON = {}));
  28293. //# sourceMappingURL=babylon.mesh.js.map
  28294. var BABYLON;
  28295. (function (BABYLON) {
  28296. var BaseSubMesh = /** @class */ (function () {
  28297. function BaseSubMesh() {
  28298. }
  28299. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28300. get: function () {
  28301. return this._materialEffect;
  28302. },
  28303. enumerable: true,
  28304. configurable: true
  28305. });
  28306. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28307. if (defines === void 0) { defines = null; }
  28308. if (this._materialEffect === effect) {
  28309. if (!effect) {
  28310. this._materialDefines = null;
  28311. }
  28312. return;
  28313. }
  28314. this._materialDefines = defines;
  28315. this._materialEffect = effect;
  28316. };
  28317. return BaseSubMesh;
  28318. }());
  28319. BABYLON.BaseSubMesh = BaseSubMesh;
  28320. var SubMesh = /** @class */ (function (_super) {
  28321. __extends(SubMesh, _super);
  28322. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28323. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28324. var _this = _super.call(this) || this;
  28325. _this.materialIndex = materialIndex;
  28326. _this.verticesStart = verticesStart;
  28327. _this.verticesCount = verticesCount;
  28328. _this.indexStart = indexStart;
  28329. _this.indexCount = indexCount;
  28330. _this._renderId = 0;
  28331. _this._mesh = mesh;
  28332. _this._renderingMesh = renderingMesh || mesh;
  28333. mesh.subMeshes.push(_this);
  28334. _this._trianglePlanes = [];
  28335. _this._id = mesh.subMeshes.length - 1;
  28336. if (createBoundingBox) {
  28337. _this.refreshBoundingInfo();
  28338. mesh.computeWorldMatrix(true);
  28339. }
  28340. return _this;
  28341. }
  28342. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28343. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28344. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28345. };
  28346. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28347. get: function () {
  28348. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28349. },
  28350. enumerable: true,
  28351. configurable: true
  28352. });
  28353. /**
  28354. * Returns the submesh BoudingInfo object.
  28355. */
  28356. SubMesh.prototype.getBoundingInfo = function () {
  28357. if (this.IsGlobal) {
  28358. return this._mesh.getBoundingInfo();
  28359. }
  28360. return this._boundingInfo;
  28361. };
  28362. /**
  28363. * Sets the submesh BoundingInfo.
  28364. * Return the SubMesh.
  28365. */
  28366. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28367. this._boundingInfo = boundingInfo;
  28368. return this;
  28369. };
  28370. /**
  28371. * Returns the mesh of the current submesh.
  28372. */
  28373. SubMesh.prototype.getMesh = function () {
  28374. return this._mesh;
  28375. };
  28376. /**
  28377. * Returns the rendering mesh of the submesh.
  28378. */
  28379. SubMesh.prototype.getRenderingMesh = function () {
  28380. return this._renderingMesh;
  28381. };
  28382. /**
  28383. * Returns the submesh material.
  28384. */
  28385. SubMesh.prototype.getMaterial = function () {
  28386. var rootMaterial = this._renderingMesh.material;
  28387. if (rootMaterial === null || rootMaterial === undefined) {
  28388. return this._mesh.getScene().defaultMaterial;
  28389. }
  28390. else if (rootMaterial.getSubMaterial) {
  28391. var multiMaterial = rootMaterial;
  28392. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28393. if (this._currentMaterial !== effectiveMaterial) {
  28394. this._currentMaterial = effectiveMaterial;
  28395. this._materialDefines = null;
  28396. }
  28397. return effectiveMaterial;
  28398. }
  28399. return rootMaterial;
  28400. };
  28401. // Methods
  28402. /**
  28403. * Sets a new updated BoundingInfo object to the submesh.
  28404. * Returns the SubMesh.
  28405. */
  28406. SubMesh.prototype.refreshBoundingInfo = function () {
  28407. this._lastColliderWorldVertices = null;
  28408. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28409. return this;
  28410. }
  28411. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28412. if (!data) {
  28413. this._boundingInfo = this._mesh.getBoundingInfo();
  28414. return this;
  28415. }
  28416. var indices = this._renderingMesh.getIndices();
  28417. var extend;
  28418. //is this the only submesh?
  28419. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28420. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28421. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28422. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28423. }
  28424. else {
  28425. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28426. }
  28427. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28428. return this;
  28429. };
  28430. SubMesh.prototype._checkCollision = function (collider) {
  28431. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28432. return boundingInfo._checkCollision(collider);
  28433. };
  28434. /**
  28435. * Updates the submesh BoundingInfo.
  28436. * Returns the Submesh.
  28437. */
  28438. SubMesh.prototype.updateBoundingInfo = function (world) {
  28439. var boundingInfo = this.getBoundingInfo();
  28440. if (!boundingInfo) {
  28441. this.refreshBoundingInfo();
  28442. boundingInfo = this.getBoundingInfo();
  28443. }
  28444. boundingInfo.update(world);
  28445. return this;
  28446. };
  28447. /**
  28448. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28449. * Boolean returned.
  28450. */
  28451. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28452. var boundingInfo = this.getBoundingInfo();
  28453. if (!boundingInfo) {
  28454. return false;
  28455. }
  28456. return boundingInfo.isInFrustum(frustumPlanes);
  28457. };
  28458. /**
  28459. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28460. * Boolean returned.
  28461. */
  28462. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28463. var boundingInfo = this.getBoundingInfo();
  28464. if (!boundingInfo) {
  28465. return false;
  28466. }
  28467. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28468. };
  28469. /**
  28470. * Renders the submesh.
  28471. * Returns it.
  28472. */
  28473. SubMesh.prototype.render = function (enableAlphaMode) {
  28474. this._renderingMesh.render(this, enableAlphaMode);
  28475. return this;
  28476. };
  28477. /**
  28478. * Returns a new Index Buffer.
  28479. * Type returned : WebGLBuffer.
  28480. */
  28481. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28482. if (!this._linesIndexBuffer) {
  28483. var linesIndices = [];
  28484. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28485. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28486. }
  28487. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28488. this.linesIndexCount = linesIndices.length;
  28489. }
  28490. return this._linesIndexBuffer;
  28491. };
  28492. /**
  28493. * True is the passed Ray intersects the submesh bounding box.
  28494. * Boolean returned.
  28495. */
  28496. SubMesh.prototype.canIntersects = function (ray) {
  28497. var boundingInfo = this.getBoundingInfo();
  28498. if (!boundingInfo) {
  28499. return false;
  28500. }
  28501. return ray.intersectsBox(boundingInfo.boundingBox);
  28502. };
  28503. /**
  28504. * Returns an object IntersectionInfo.
  28505. */
  28506. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28507. var intersectInfo = null;
  28508. // LineMesh first as it's also a Mesh...
  28509. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28510. var lineMesh = this._mesh;
  28511. // Line test
  28512. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28513. var p0 = positions[indices[index]];
  28514. var p1 = positions[indices[index + 1]];
  28515. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28516. if (length < 0) {
  28517. continue;
  28518. }
  28519. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28520. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28521. if (fastCheck) {
  28522. break;
  28523. }
  28524. }
  28525. }
  28526. }
  28527. else {
  28528. // Triangles test
  28529. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28530. var p0 = positions[indices[index]];
  28531. var p1 = positions[indices[index + 1]];
  28532. var p2 = positions[indices[index + 2]];
  28533. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28534. if (currentIntersectInfo) {
  28535. if (currentIntersectInfo.distance < 0) {
  28536. continue;
  28537. }
  28538. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28539. intersectInfo = currentIntersectInfo;
  28540. intersectInfo.faceId = index / 3;
  28541. if (fastCheck) {
  28542. break;
  28543. }
  28544. }
  28545. }
  28546. }
  28547. }
  28548. return intersectInfo;
  28549. };
  28550. SubMesh.prototype._rebuild = function () {
  28551. if (this._linesIndexBuffer) {
  28552. this._linesIndexBuffer = null;
  28553. }
  28554. };
  28555. // Clone
  28556. /**
  28557. * Creates a new Submesh from the passed Mesh.
  28558. */
  28559. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28560. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28561. if (!this.IsGlobal) {
  28562. var boundingInfo = this.getBoundingInfo();
  28563. if (!boundingInfo) {
  28564. return result;
  28565. }
  28566. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28567. }
  28568. return result;
  28569. };
  28570. // Dispose
  28571. /**
  28572. * Disposes the Submesh.
  28573. * Returns nothing.
  28574. */
  28575. SubMesh.prototype.dispose = function () {
  28576. if (this._linesIndexBuffer) {
  28577. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28578. this._linesIndexBuffer = null;
  28579. }
  28580. // Remove from mesh
  28581. var index = this._mesh.subMeshes.indexOf(this);
  28582. this._mesh.subMeshes.splice(index, 1);
  28583. };
  28584. // Statics
  28585. /**
  28586. * Creates a new Submesh from the passed parameters :
  28587. * - materialIndex (integer) : the index of the main mesh material.
  28588. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28589. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28590. * - mesh (Mesh) : the main mesh to create the submesh from.
  28591. * - renderingMesh (optional Mesh) : rendering mesh.
  28592. */
  28593. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28594. var minVertexIndex = Number.MAX_VALUE;
  28595. var maxVertexIndex = -Number.MAX_VALUE;
  28596. renderingMesh = (renderingMesh || mesh);
  28597. var indices = renderingMesh.getIndices();
  28598. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28599. var vertexIndex = indices[index];
  28600. if (vertexIndex < minVertexIndex)
  28601. minVertexIndex = vertexIndex;
  28602. if (vertexIndex > maxVertexIndex)
  28603. maxVertexIndex = vertexIndex;
  28604. }
  28605. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28606. };
  28607. return SubMesh;
  28608. }(BaseSubMesh));
  28609. BABYLON.SubMesh = SubMesh;
  28610. })(BABYLON || (BABYLON = {}));
  28611. //# sourceMappingURL=babylon.subMesh.js.map
  28612. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28613. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28614. s = arguments[i];
  28615. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28616. t[p] = s[p];
  28617. }
  28618. return t;
  28619. };
  28620. var BABYLON;
  28621. (function (BABYLON) {
  28622. var MaterialDefines = /** @class */ (function () {
  28623. function MaterialDefines() {
  28624. this._isDirty = true;
  28625. this._areLightsDirty = true;
  28626. this._areAttributesDirty = true;
  28627. this._areTexturesDirty = true;
  28628. this._areFresnelDirty = true;
  28629. this._areMiscDirty = true;
  28630. this._areImageProcessingDirty = true;
  28631. this._normals = false;
  28632. this._uvs = false;
  28633. this._needNormals = false;
  28634. this._needUVs = false;
  28635. }
  28636. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28637. get: function () {
  28638. return this._isDirty;
  28639. },
  28640. enumerable: true,
  28641. configurable: true
  28642. });
  28643. MaterialDefines.prototype.markAsProcessed = function () {
  28644. this._isDirty = false;
  28645. this._areAttributesDirty = false;
  28646. this._areTexturesDirty = false;
  28647. this._areFresnelDirty = false;
  28648. this._areLightsDirty = false;
  28649. this._areMiscDirty = false;
  28650. this._areImageProcessingDirty = false;
  28651. };
  28652. MaterialDefines.prototype.markAsUnprocessed = function () {
  28653. this._isDirty = true;
  28654. };
  28655. MaterialDefines.prototype.markAllAsDirty = function () {
  28656. this._areTexturesDirty = true;
  28657. this._areAttributesDirty = true;
  28658. this._areLightsDirty = true;
  28659. this._areFresnelDirty = true;
  28660. this._areMiscDirty = true;
  28661. this._areImageProcessingDirty = true;
  28662. this._isDirty = true;
  28663. };
  28664. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28665. this._areImageProcessingDirty = true;
  28666. this._isDirty = true;
  28667. };
  28668. MaterialDefines.prototype.markAsLightDirty = function () {
  28669. this._areLightsDirty = true;
  28670. this._isDirty = true;
  28671. };
  28672. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28673. this._areAttributesDirty = true;
  28674. this._isDirty = true;
  28675. };
  28676. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28677. this._areTexturesDirty = true;
  28678. this._isDirty = true;
  28679. };
  28680. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28681. this._areFresnelDirty = true;
  28682. this._isDirty = true;
  28683. };
  28684. MaterialDefines.prototype.markAsMiscDirty = function () {
  28685. this._areMiscDirty = true;
  28686. this._isDirty = true;
  28687. };
  28688. MaterialDefines.prototype.rebuild = function () {
  28689. if (this._keys) {
  28690. delete this._keys;
  28691. }
  28692. this._keys = [];
  28693. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28694. var key = _a[_i];
  28695. if (key[0] === "_") {
  28696. continue;
  28697. }
  28698. this._keys.push(key);
  28699. }
  28700. };
  28701. MaterialDefines.prototype.isEqual = function (other) {
  28702. if (this._keys.length !== other._keys.length) {
  28703. return false;
  28704. }
  28705. for (var index = 0; index < this._keys.length; index++) {
  28706. var prop = this._keys[index];
  28707. if (this[prop] !== other[prop]) {
  28708. return false;
  28709. }
  28710. }
  28711. return true;
  28712. };
  28713. MaterialDefines.prototype.cloneTo = function (other) {
  28714. if (this._keys.length !== other._keys.length) {
  28715. other._keys = this._keys.slice(0);
  28716. }
  28717. for (var index = 0; index < this._keys.length; index++) {
  28718. var prop = this._keys[index];
  28719. other[prop] = this[prop];
  28720. }
  28721. };
  28722. MaterialDefines.prototype.reset = function () {
  28723. for (var index = 0; index < this._keys.length; index++) {
  28724. var prop = this._keys[index];
  28725. if (typeof (this[prop]) === "number") {
  28726. this[prop] = 0;
  28727. }
  28728. else {
  28729. this[prop] = false;
  28730. }
  28731. }
  28732. };
  28733. MaterialDefines.prototype.toString = function () {
  28734. var result = "";
  28735. for (var index = 0; index < this._keys.length; index++) {
  28736. var prop = this._keys[index];
  28737. var value = this[prop];
  28738. if (typeof (value) === "number") {
  28739. result += "#define " + prop + " " + this[prop] + "\n";
  28740. }
  28741. else if (value) {
  28742. result += "#define " + prop + "\n";
  28743. }
  28744. }
  28745. return result;
  28746. };
  28747. return MaterialDefines;
  28748. }());
  28749. BABYLON.MaterialDefines = MaterialDefines;
  28750. var Material = /** @class */ (function () {
  28751. function Material(name, scene, doNotAdd) {
  28752. this.checkReadyOnEveryCall = false;
  28753. this.checkReadyOnlyOnce = false;
  28754. this.state = "";
  28755. this.alpha = 1.0;
  28756. this._backFaceCulling = true;
  28757. this.doNotSerialize = false;
  28758. this.storeEffectOnSubMeshes = false;
  28759. /**
  28760. * An event triggered when the material is disposed.
  28761. * @type {BABYLON.Observable}
  28762. */
  28763. this.onDisposeObservable = new BABYLON.Observable();
  28764. /**
  28765. * An event triggered when the material is bound.
  28766. * @type {BABYLON.Observable}
  28767. */
  28768. this.onBindObservable = new BABYLON.Observable();
  28769. /**
  28770. * An event triggered when the material is unbound.
  28771. * @type {BABYLON.Observable}
  28772. */
  28773. this.onUnBindObservable = new BABYLON.Observable();
  28774. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28775. this._needDepthPrePass = false;
  28776. this.disableDepthWrite = false;
  28777. this.forceDepthWrite = false;
  28778. this.separateCullingPass = false;
  28779. this._fogEnabled = true;
  28780. this.pointSize = 1.0;
  28781. this.zOffset = 0;
  28782. this._wasPreviouslyReady = false;
  28783. this._fillMode = Material.TriangleFillMode;
  28784. this.name = name;
  28785. this.id = name || BABYLON.Tools.RandomId();
  28786. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28787. if (this._scene.useRightHandedSystem) {
  28788. this.sideOrientation = Material.ClockWiseSideOrientation;
  28789. }
  28790. else {
  28791. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28792. }
  28793. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28794. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28795. if (!doNotAdd) {
  28796. this._scene.materials.push(this);
  28797. }
  28798. }
  28799. Object.defineProperty(Material, "TriangleFillMode", {
  28800. get: function () {
  28801. return Material._TriangleFillMode;
  28802. },
  28803. enumerable: true,
  28804. configurable: true
  28805. });
  28806. Object.defineProperty(Material, "WireFrameFillMode", {
  28807. get: function () {
  28808. return Material._WireFrameFillMode;
  28809. },
  28810. enumerable: true,
  28811. configurable: true
  28812. });
  28813. Object.defineProperty(Material, "PointFillMode", {
  28814. get: function () {
  28815. return Material._PointFillMode;
  28816. },
  28817. enumerable: true,
  28818. configurable: true
  28819. });
  28820. Object.defineProperty(Material, "PointListDrawMode", {
  28821. get: function () {
  28822. return Material._PointListDrawMode;
  28823. },
  28824. enumerable: true,
  28825. configurable: true
  28826. });
  28827. Object.defineProperty(Material, "LineListDrawMode", {
  28828. get: function () {
  28829. return Material._LineListDrawMode;
  28830. },
  28831. enumerable: true,
  28832. configurable: true
  28833. });
  28834. Object.defineProperty(Material, "LineLoopDrawMode", {
  28835. get: function () {
  28836. return Material._LineLoopDrawMode;
  28837. },
  28838. enumerable: true,
  28839. configurable: true
  28840. });
  28841. Object.defineProperty(Material, "LineStripDrawMode", {
  28842. get: function () {
  28843. return Material._LineStripDrawMode;
  28844. },
  28845. enumerable: true,
  28846. configurable: true
  28847. });
  28848. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28849. get: function () {
  28850. return Material._TriangleStripDrawMode;
  28851. },
  28852. enumerable: true,
  28853. configurable: true
  28854. });
  28855. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28856. get: function () {
  28857. return Material._TriangleFanDrawMode;
  28858. },
  28859. enumerable: true,
  28860. configurable: true
  28861. });
  28862. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28863. get: function () {
  28864. return Material._ClockWiseSideOrientation;
  28865. },
  28866. enumerable: true,
  28867. configurable: true
  28868. });
  28869. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28870. get: function () {
  28871. return Material._CounterClockWiseSideOrientation;
  28872. },
  28873. enumerable: true,
  28874. configurable: true
  28875. });
  28876. Object.defineProperty(Material, "TextureDirtyFlag", {
  28877. get: function () {
  28878. return Material._TextureDirtyFlag;
  28879. },
  28880. enumerable: true,
  28881. configurable: true
  28882. });
  28883. Object.defineProperty(Material, "LightDirtyFlag", {
  28884. get: function () {
  28885. return Material._LightDirtyFlag;
  28886. },
  28887. enumerable: true,
  28888. configurable: true
  28889. });
  28890. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28891. get: function () {
  28892. return Material._FresnelDirtyFlag;
  28893. },
  28894. enumerable: true,
  28895. configurable: true
  28896. });
  28897. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28898. get: function () {
  28899. return Material._AttributesDirtyFlag;
  28900. },
  28901. enumerable: true,
  28902. configurable: true
  28903. });
  28904. Object.defineProperty(Material, "MiscDirtyFlag", {
  28905. get: function () {
  28906. return Material._MiscDirtyFlag;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28912. get: function () {
  28913. return this._backFaceCulling;
  28914. },
  28915. set: function (value) {
  28916. if (this._backFaceCulling === value) {
  28917. return;
  28918. }
  28919. this._backFaceCulling = value;
  28920. this.markAsDirty(Material.TextureDirtyFlag);
  28921. },
  28922. enumerable: true,
  28923. configurable: true
  28924. });
  28925. Object.defineProperty(Material.prototype, "onDispose", {
  28926. set: function (callback) {
  28927. if (this._onDisposeObserver) {
  28928. this.onDisposeObservable.remove(this._onDisposeObserver);
  28929. }
  28930. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28931. },
  28932. enumerable: true,
  28933. configurable: true
  28934. });
  28935. Object.defineProperty(Material.prototype, "onBind", {
  28936. set: function (callback) {
  28937. if (this._onBindObserver) {
  28938. this.onBindObservable.remove(this._onBindObserver);
  28939. }
  28940. this._onBindObserver = this.onBindObservable.add(callback);
  28941. },
  28942. enumerable: true,
  28943. configurable: true
  28944. });
  28945. Object.defineProperty(Material.prototype, "alphaMode", {
  28946. get: function () {
  28947. return this._alphaMode;
  28948. },
  28949. set: function (value) {
  28950. if (this._alphaMode === value) {
  28951. return;
  28952. }
  28953. this._alphaMode = value;
  28954. this.markAsDirty(Material.TextureDirtyFlag);
  28955. },
  28956. enumerable: true,
  28957. configurable: true
  28958. });
  28959. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28960. get: function () {
  28961. return this._needDepthPrePass;
  28962. },
  28963. set: function (value) {
  28964. if (this._needDepthPrePass === value) {
  28965. return;
  28966. }
  28967. this._needDepthPrePass = value;
  28968. if (this._needDepthPrePass) {
  28969. this.checkReadyOnEveryCall = true;
  28970. }
  28971. },
  28972. enumerable: true,
  28973. configurable: true
  28974. });
  28975. Object.defineProperty(Material.prototype, "fogEnabled", {
  28976. get: function () {
  28977. return this._fogEnabled;
  28978. },
  28979. set: function (value) {
  28980. if (this._fogEnabled === value) {
  28981. return;
  28982. }
  28983. this._fogEnabled = value;
  28984. this.markAsDirty(Material.MiscDirtyFlag);
  28985. },
  28986. enumerable: true,
  28987. configurable: true
  28988. });
  28989. Object.defineProperty(Material.prototype, "wireframe", {
  28990. get: function () {
  28991. return this._fillMode === Material.WireFrameFillMode;
  28992. },
  28993. set: function (value) {
  28994. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28995. },
  28996. enumerable: true,
  28997. configurable: true
  28998. });
  28999. Object.defineProperty(Material.prototype, "pointsCloud", {
  29000. get: function () {
  29001. return this._fillMode === Material.PointFillMode;
  29002. },
  29003. set: function (value) {
  29004. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29005. },
  29006. enumerable: true,
  29007. configurable: true
  29008. });
  29009. Object.defineProperty(Material.prototype, "fillMode", {
  29010. get: function () {
  29011. return this._fillMode;
  29012. },
  29013. set: function (value) {
  29014. if (this._fillMode === value) {
  29015. return;
  29016. }
  29017. this._fillMode = value;
  29018. this.markAsDirty(Material.MiscDirtyFlag);
  29019. },
  29020. enumerable: true,
  29021. configurable: true
  29022. });
  29023. /**
  29024. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29025. * subclasses should override adding information pertainent to themselves
  29026. */
  29027. Material.prototype.toString = function (fullDetails) {
  29028. var ret = "Name: " + this.name;
  29029. if (fullDetails) {
  29030. }
  29031. return ret;
  29032. };
  29033. /**
  29034. * Child classes can use it to update shaders
  29035. */
  29036. Material.prototype.getClassName = function () {
  29037. return "Material";
  29038. };
  29039. Object.defineProperty(Material.prototype, "isFrozen", {
  29040. get: function () {
  29041. return this.checkReadyOnlyOnce;
  29042. },
  29043. enumerable: true,
  29044. configurable: true
  29045. });
  29046. Material.prototype.freeze = function () {
  29047. this.checkReadyOnlyOnce = true;
  29048. };
  29049. Material.prototype.unfreeze = function () {
  29050. this.checkReadyOnlyOnce = false;
  29051. };
  29052. Material.prototype.isReady = function (mesh, useInstances) {
  29053. return true;
  29054. };
  29055. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29056. return false;
  29057. };
  29058. Material.prototype.getEffect = function () {
  29059. return this._effect;
  29060. };
  29061. Material.prototype.getScene = function () {
  29062. return this._scene;
  29063. };
  29064. Material.prototype.needAlphaBlending = function () {
  29065. return (this.alpha < 1.0);
  29066. };
  29067. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29068. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29069. };
  29070. Material.prototype.needAlphaTesting = function () {
  29071. return false;
  29072. };
  29073. Material.prototype.getAlphaTestTexture = function () {
  29074. return null;
  29075. };
  29076. Material.prototype.markDirty = function () {
  29077. this._wasPreviouslyReady = false;
  29078. };
  29079. Material.prototype._preBind = function (effect, overrideOrientation) {
  29080. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29081. var engine = this._scene.getEngine();
  29082. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29083. var reverse = orientation === Material.ClockWiseSideOrientation;
  29084. engine.enableEffect(effect ? effect : this._effect);
  29085. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29086. return reverse;
  29087. };
  29088. Material.prototype.bind = function (world, mesh) {
  29089. };
  29090. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29091. };
  29092. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29093. };
  29094. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29095. sceneUbo.bindToEffect(effect, "Scene");
  29096. };
  29097. Material.prototype.bindView = function (effect) {
  29098. if (!this._useUBO) {
  29099. effect.setMatrix("view", this.getScene().getViewMatrix());
  29100. }
  29101. else {
  29102. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29103. }
  29104. };
  29105. Material.prototype.bindViewProjection = function (effect) {
  29106. if (!this._useUBO) {
  29107. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29108. }
  29109. else {
  29110. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29111. }
  29112. };
  29113. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29114. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29115. };
  29116. Material.prototype._afterBind = function (mesh) {
  29117. this._scene._cachedMaterial = this;
  29118. if (mesh) {
  29119. this._scene._cachedVisibility = mesh.visibility;
  29120. }
  29121. else {
  29122. this._scene._cachedVisibility = 1;
  29123. }
  29124. if (mesh) {
  29125. this.onBindObservable.notifyObservers(mesh);
  29126. }
  29127. if (this.disableDepthWrite) {
  29128. var engine = this._scene.getEngine();
  29129. this._cachedDepthWriteState = engine.getDepthWrite();
  29130. engine.setDepthWrite(false);
  29131. }
  29132. };
  29133. Material.prototype.unbind = function () {
  29134. this.onUnBindObservable.notifyObservers(this);
  29135. if (this.disableDepthWrite) {
  29136. var engine = this._scene.getEngine();
  29137. engine.setDepthWrite(this._cachedDepthWriteState);
  29138. }
  29139. };
  29140. Material.prototype.getActiveTextures = function () {
  29141. return [];
  29142. };
  29143. Material.prototype.hasTexture = function (texture) {
  29144. return false;
  29145. };
  29146. Material.prototype.clone = function (name) {
  29147. return null;
  29148. };
  29149. Material.prototype.getBindedMeshes = function () {
  29150. var result = new Array();
  29151. for (var index = 0; index < this._scene.meshes.length; index++) {
  29152. var mesh = this._scene.meshes[index];
  29153. if (mesh.material === this) {
  29154. result.push(mesh);
  29155. }
  29156. }
  29157. return result;
  29158. };
  29159. /**
  29160. * Force shader compilation including textures ready check
  29161. */
  29162. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29163. var _this = this;
  29164. var localOptions = __assign({ clipPlane: false }, options);
  29165. var subMesh = new BABYLON.BaseSubMesh();
  29166. var scene = this.getScene();
  29167. var checkReady = function () {
  29168. if (!_this._scene || !_this._scene.getEngine()) {
  29169. return;
  29170. }
  29171. if (subMesh._materialDefines) {
  29172. subMesh._materialDefines._renderId = -1;
  29173. }
  29174. var clipPlaneState = scene.clipPlane;
  29175. if (localOptions.clipPlane) {
  29176. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29177. }
  29178. if (_this.storeEffectOnSubMeshes) {
  29179. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29180. if (onCompiled) {
  29181. onCompiled(_this);
  29182. }
  29183. }
  29184. else {
  29185. setTimeout(checkReady, 16);
  29186. }
  29187. }
  29188. else {
  29189. if (_this.isReady(mesh)) {
  29190. if (onCompiled) {
  29191. onCompiled(_this);
  29192. }
  29193. }
  29194. else {
  29195. setTimeout(checkReady, 16);
  29196. }
  29197. }
  29198. if (options && options.clipPlane) {
  29199. scene.clipPlane = clipPlaneState;
  29200. }
  29201. };
  29202. checkReady();
  29203. };
  29204. Material.prototype.markAsDirty = function (flag) {
  29205. if (flag & Material.TextureDirtyFlag) {
  29206. this._markAllSubMeshesAsTexturesDirty();
  29207. }
  29208. if (flag & Material.LightDirtyFlag) {
  29209. this._markAllSubMeshesAsLightsDirty();
  29210. }
  29211. if (flag & Material.FresnelDirtyFlag) {
  29212. this._markAllSubMeshesAsFresnelDirty();
  29213. }
  29214. if (flag & Material.AttributesDirtyFlag) {
  29215. this._markAllSubMeshesAsAttributesDirty();
  29216. }
  29217. if (flag & Material.MiscDirtyFlag) {
  29218. this._markAllSubMeshesAsMiscDirty();
  29219. }
  29220. this.getScene().resetCachedMaterial();
  29221. };
  29222. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29223. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29224. var mesh = _a[_i];
  29225. if (!mesh.subMeshes) {
  29226. continue;
  29227. }
  29228. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29229. var subMesh = _c[_b];
  29230. if (subMesh.getMaterial() !== this) {
  29231. continue;
  29232. }
  29233. if (!subMesh._materialDefines) {
  29234. continue;
  29235. }
  29236. func(subMesh._materialDefines);
  29237. }
  29238. }
  29239. };
  29240. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29241. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29242. };
  29243. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29244. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29245. };
  29246. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29247. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29248. };
  29249. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29250. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29251. };
  29252. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29253. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29254. };
  29255. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29256. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29257. };
  29258. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29259. // Animations
  29260. this.getScene().stopAnimation(this);
  29261. // Remove from scene
  29262. var index = this._scene.materials.indexOf(this);
  29263. if (index >= 0) {
  29264. this._scene.materials.splice(index, 1);
  29265. }
  29266. // Remove from meshes
  29267. for (index = 0; index < this._scene.meshes.length; index++) {
  29268. var mesh = this._scene.meshes[index];
  29269. if (mesh.material === this) {
  29270. mesh.material = null;
  29271. if (mesh.geometry) {
  29272. var geometry = (mesh.geometry);
  29273. if (this.storeEffectOnSubMeshes) {
  29274. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29275. var subMesh = _a[_i];
  29276. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29277. if (forceDisposeEffect && subMesh._materialEffect) {
  29278. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29279. }
  29280. }
  29281. }
  29282. else {
  29283. geometry._releaseVertexArrayObject(this._effect);
  29284. }
  29285. }
  29286. }
  29287. }
  29288. this._uniformBuffer.dispose();
  29289. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29290. if (forceDisposeEffect && this._effect) {
  29291. if (!this.storeEffectOnSubMeshes) {
  29292. this._scene.getEngine()._releaseEffect(this._effect);
  29293. }
  29294. this._effect = null;
  29295. }
  29296. // Callback
  29297. this.onDisposeObservable.notifyObservers(this);
  29298. this.onDisposeObservable.clear();
  29299. this.onBindObservable.clear();
  29300. this.onUnBindObservable.clear();
  29301. };
  29302. Material.prototype.serialize = function () {
  29303. return BABYLON.SerializationHelper.Serialize(this);
  29304. };
  29305. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29306. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29307. multiMaterial.id = parsedMultiMaterial.id;
  29308. if (BABYLON.Tags) {
  29309. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29310. }
  29311. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29312. var subMatId = parsedMultiMaterial.materials[matIndex];
  29313. if (subMatId) {
  29314. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29315. }
  29316. else {
  29317. multiMaterial.subMaterials.push(null);
  29318. }
  29319. }
  29320. return multiMaterial;
  29321. };
  29322. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29323. if (!parsedMaterial.customType) {
  29324. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29325. }
  29326. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29327. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29328. if (!BABYLON.LegacyPBRMaterial) {
  29329. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29330. return;
  29331. }
  29332. }
  29333. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29334. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29335. ;
  29336. };
  29337. // Triangle views
  29338. Material._TriangleFillMode = 0;
  29339. Material._WireFrameFillMode = 1;
  29340. Material._PointFillMode = 2;
  29341. // Draw modes
  29342. Material._PointListDrawMode = 3;
  29343. Material._LineListDrawMode = 4;
  29344. Material._LineLoopDrawMode = 5;
  29345. Material._LineStripDrawMode = 6;
  29346. Material._TriangleStripDrawMode = 7;
  29347. Material._TriangleFanDrawMode = 8;
  29348. Material._ClockWiseSideOrientation = 0;
  29349. Material._CounterClockWiseSideOrientation = 1;
  29350. Material._TextureDirtyFlag = 1;
  29351. Material._LightDirtyFlag = 2;
  29352. Material._FresnelDirtyFlag = 4;
  29353. Material._AttributesDirtyFlag = 8;
  29354. Material._MiscDirtyFlag = 16;
  29355. __decorate([
  29356. BABYLON.serialize()
  29357. ], Material.prototype, "id", void 0);
  29358. __decorate([
  29359. BABYLON.serialize()
  29360. ], Material.prototype, "name", void 0);
  29361. __decorate([
  29362. BABYLON.serialize()
  29363. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29364. __decorate([
  29365. BABYLON.serialize()
  29366. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29367. __decorate([
  29368. BABYLON.serialize()
  29369. ], Material.prototype, "state", void 0);
  29370. __decorate([
  29371. BABYLON.serialize()
  29372. ], Material.prototype, "alpha", void 0);
  29373. __decorate([
  29374. BABYLON.serialize("backFaceCulling")
  29375. ], Material.prototype, "_backFaceCulling", void 0);
  29376. __decorate([
  29377. BABYLON.serialize()
  29378. ], Material.prototype, "sideOrientation", void 0);
  29379. __decorate([
  29380. BABYLON.serialize("alphaMode")
  29381. ], Material.prototype, "_alphaMode", void 0);
  29382. __decorate([
  29383. BABYLON.serialize()
  29384. ], Material.prototype, "_needDepthPrePass", void 0);
  29385. __decorate([
  29386. BABYLON.serialize()
  29387. ], Material.prototype, "disableDepthWrite", void 0);
  29388. __decorate([
  29389. BABYLON.serialize()
  29390. ], Material.prototype, "forceDepthWrite", void 0);
  29391. __decorate([
  29392. BABYLON.serialize()
  29393. ], Material.prototype, "separateCullingPass", void 0);
  29394. __decorate([
  29395. BABYLON.serialize("fogEnabled")
  29396. ], Material.prototype, "_fogEnabled", void 0);
  29397. __decorate([
  29398. BABYLON.serialize()
  29399. ], Material.prototype, "pointSize", void 0);
  29400. __decorate([
  29401. BABYLON.serialize()
  29402. ], Material.prototype, "zOffset", void 0);
  29403. __decorate([
  29404. BABYLON.serialize()
  29405. ], Material.prototype, "wireframe", null);
  29406. __decorate([
  29407. BABYLON.serialize()
  29408. ], Material.prototype, "pointsCloud", null);
  29409. __decorate([
  29410. BABYLON.serialize()
  29411. ], Material.prototype, "fillMode", null);
  29412. return Material;
  29413. }());
  29414. BABYLON.Material = Material;
  29415. })(BABYLON || (BABYLON = {}));
  29416. //# sourceMappingURL=babylon.material.js.map
  29417. var BABYLON;
  29418. (function (BABYLON) {
  29419. var UniformBuffer = /** @class */ (function () {
  29420. /**
  29421. * Uniform buffer objects.
  29422. *
  29423. * Handles blocks of uniform on the GPU.
  29424. *
  29425. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29426. *
  29427. * For more information, please refer to :
  29428. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29429. */
  29430. function UniformBuffer(engine, data, dynamic) {
  29431. this._engine = engine;
  29432. this._noUBO = !engine.supportsUniformBuffers;
  29433. this._dynamic = dynamic;
  29434. this._data = data || [];
  29435. this._uniformLocations = {};
  29436. this._uniformSizes = {};
  29437. this._uniformLocationPointer = 0;
  29438. this._needSync = false;
  29439. if (this._noUBO) {
  29440. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29441. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29442. this.updateFloat = this._updateFloatForEffect;
  29443. this.updateFloat2 = this._updateFloat2ForEffect;
  29444. this.updateFloat3 = this._updateFloat3ForEffect;
  29445. this.updateFloat4 = this._updateFloat4ForEffect;
  29446. this.updateMatrix = this._updateMatrixForEffect;
  29447. this.updateVector3 = this._updateVector3ForEffect;
  29448. this.updateVector4 = this._updateVector4ForEffect;
  29449. this.updateColor3 = this._updateColor3ForEffect;
  29450. this.updateColor4 = this._updateColor4ForEffect;
  29451. }
  29452. else {
  29453. this._engine._uniformBuffers.push(this);
  29454. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29455. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29456. this.updateFloat = this._updateFloatForUniform;
  29457. this.updateFloat2 = this._updateFloat2ForUniform;
  29458. this.updateFloat3 = this._updateFloat3ForUniform;
  29459. this.updateFloat4 = this._updateFloat4ForUniform;
  29460. this.updateMatrix = this._updateMatrixForUniform;
  29461. this.updateVector3 = this._updateVector3ForUniform;
  29462. this.updateVector4 = this._updateVector4ForUniform;
  29463. this.updateColor3 = this._updateColor3ForUniform;
  29464. this.updateColor4 = this._updateColor4ForUniform;
  29465. }
  29466. }
  29467. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29468. // Properties
  29469. /**
  29470. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29471. * or just falling back on setUniformXXX calls.
  29472. */
  29473. get: function () {
  29474. return !this._noUBO;
  29475. },
  29476. enumerable: true,
  29477. configurable: true
  29478. });
  29479. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29480. /**
  29481. * Indicates if the WebGL underlying uniform buffer is in sync
  29482. * with the javascript cache data.
  29483. */
  29484. get: function () {
  29485. return !this._needSync;
  29486. },
  29487. enumerable: true,
  29488. configurable: true
  29489. });
  29490. /**
  29491. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29492. * Also, a dynamic UniformBuffer will disable cache verification and always
  29493. * update the underlying WebGL uniform buffer to the GPU.
  29494. */
  29495. UniformBuffer.prototype.isDynamic = function () {
  29496. return this._dynamic !== undefined;
  29497. };
  29498. /**
  29499. * The data cache on JS side.
  29500. */
  29501. UniformBuffer.prototype.getData = function () {
  29502. return this._bufferData;
  29503. };
  29504. /**
  29505. * The underlying WebGL Uniform buffer.
  29506. */
  29507. UniformBuffer.prototype.getBuffer = function () {
  29508. return this._buffer;
  29509. };
  29510. /**
  29511. * std140 layout specifies how to align data within an UBO structure.
  29512. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29513. * for specs.
  29514. */
  29515. UniformBuffer.prototype._fillAlignment = function (size) {
  29516. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29517. // and 4x4 matrices
  29518. // TODO : change if other types are used
  29519. var alignment;
  29520. if (size <= 2) {
  29521. alignment = size;
  29522. }
  29523. else {
  29524. alignment = 4;
  29525. }
  29526. if ((this._uniformLocationPointer % alignment) !== 0) {
  29527. var oldPointer = this._uniformLocationPointer;
  29528. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29529. var diff = this._uniformLocationPointer - oldPointer;
  29530. for (var i = 0; i < diff; i++) {
  29531. this._data.push(0);
  29532. }
  29533. }
  29534. };
  29535. /**
  29536. * Adds an uniform in the buffer.
  29537. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29538. * for the layout to be correct !
  29539. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29540. * @param {number|number[]} size Data size, or data directly.
  29541. */
  29542. UniformBuffer.prototype.addUniform = function (name, size) {
  29543. if (this._noUBO) {
  29544. return;
  29545. }
  29546. if (this._uniformLocations[name] !== undefined) {
  29547. // Already existing uniform
  29548. return;
  29549. }
  29550. // This function must be called in the order of the shader layout !
  29551. // size can be the size of the uniform, or data directly
  29552. var data;
  29553. if (size instanceof Array) {
  29554. data = size;
  29555. size = data.length;
  29556. }
  29557. else {
  29558. size = size;
  29559. data = [];
  29560. // Fill with zeros
  29561. for (var i = 0; i < size; i++) {
  29562. data.push(0);
  29563. }
  29564. }
  29565. this._fillAlignment(size);
  29566. this._uniformSizes[name] = size;
  29567. this._uniformLocations[name] = this._uniformLocationPointer;
  29568. this._uniformLocationPointer += size;
  29569. for (var i = 0; i < size; i++) {
  29570. this._data.push(data[i]);
  29571. }
  29572. this._needSync = true;
  29573. };
  29574. /**
  29575. * Wrapper for addUniform.
  29576. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29577. * @param {Matrix} mat A 4x4 matrix.
  29578. */
  29579. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29580. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29581. };
  29582. /**
  29583. * Wrapper for addUniform.
  29584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29585. * @param {number} x
  29586. * @param {number} y
  29587. */
  29588. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29589. var temp = [x, y];
  29590. this.addUniform(name, temp);
  29591. };
  29592. /**
  29593. * Wrapper for addUniform.
  29594. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29595. * @param {number} x
  29596. * @param {number} y
  29597. * @param {number} z
  29598. */
  29599. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29600. var temp = [x, y, z];
  29601. this.addUniform(name, temp);
  29602. };
  29603. /**
  29604. * Wrapper for addUniform.
  29605. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29606. * @param {Color3} color
  29607. */
  29608. UniformBuffer.prototype.addColor3 = function (name, color) {
  29609. var temp = new Array();
  29610. color.toArray(temp);
  29611. this.addUniform(name, temp);
  29612. };
  29613. /**
  29614. * Wrapper for addUniform.
  29615. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29616. * @param {Color3} color
  29617. * @param {number} alpha
  29618. */
  29619. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29620. var temp = new Array();
  29621. color.toArray(temp);
  29622. temp.push(alpha);
  29623. this.addUniform(name, temp);
  29624. };
  29625. /**
  29626. * Wrapper for addUniform.
  29627. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29628. * @param {Vector3} vector
  29629. */
  29630. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29631. var temp = new Array();
  29632. vector.toArray(temp);
  29633. this.addUniform(name, temp);
  29634. };
  29635. /**
  29636. * Wrapper for addUniform.
  29637. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29638. */
  29639. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29640. this.addUniform(name, 12);
  29641. };
  29642. /**
  29643. * Wrapper for addUniform.
  29644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29645. */
  29646. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29647. this.addUniform(name, 8);
  29648. };
  29649. /**
  29650. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29651. */
  29652. UniformBuffer.prototype.create = function () {
  29653. if (this._noUBO) {
  29654. return;
  29655. }
  29656. if (this._buffer) {
  29657. return; // nothing to do
  29658. }
  29659. // See spec, alignment must be filled as a vec4
  29660. this._fillAlignment(4);
  29661. this._bufferData = new Float32Array(this._data);
  29662. this._rebuild();
  29663. this._needSync = true;
  29664. };
  29665. UniformBuffer.prototype._rebuild = function () {
  29666. if (this._noUBO) {
  29667. return;
  29668. }
  29669. if (this._dynamic) {
  29670. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29671. }
  29672. else {
  29673. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29674. }
  29675. };
  29676. /**
  29677. * Updates the WebGL Uniform Buffer on the GPU.
  29678. * If the `dynamic` flag is set to true, no cache comparison is done.
  29679. * Otherwise, the buffer will be updated only if the cache differs.
  29680. */
  29681. UniformBuffer.prototype.update = function () {
  29682. if (!this._buffer) {
  29683. this.create();
  29684. return;
  29685. }
  29686. if (!this._dynamic && !this._needSync) {
  29687. return;
  29688. }
  29689. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29690. this._needSync = false;
  29691. };
  29692. /**
  29693. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29694. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29695. * @param {number[]|Float32Array} data Flattened data
  29696. * @param {number} size Size of the data.
  29697. */
  29698. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29699. var location = this._uniformLocations[uniformName];
  29700. if (location === undefined) {
  29701. if (this._buffer) {
  29702. // Cannot add an uniform if the buffer is already created
  29703. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29704. return;
  29705. }
  29706. this.addUniform(uniformName, size);
  29707. location = this._uniformLocations[uniformName];
  29708. }
  29709. if (!this._buffer) {
  29710. this.create();
  29711. }
  29712. if (!this._dynamic) {
  29713. // Cache for static uniform buffers
  29714. var changed = false;
  29715. for (var i = 0; i < size; i++) {
  29716. if (this._bufferData[location + i] !== data[i]) {
  29717. changed = true;
  29718. this._bufferData[location + i] = data[i];
  29719. }
  29720. }
  29721. this._needSync = this._needSync || changed;
  29722. }
  29723. else {
  29724. // No cache for dynamic
  29725. for (var i = 0; i < size; i++) {
  29726. this._bufferData[location + i] = data[i];
  29727. }
  29728. }
  29729. };
  29730. // Update methods
  29731. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29732. // To match std140, matrix must be realigned
  29733. for (var i = 0; i < 3; i++) {
  29734. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29735. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29736. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29737. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29738. }
  29739. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29740. };
  29741. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29742. this._currentEffect.setMatrix3x3(name, matrix);
  29743. };
  29744. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29745. this._currentEffect.setMatrix2x2(name, matrix);
  29746. };
  29747. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29748. // To match std140, matrix must be realigned
  29749. for (var i = 0; i < 2; i++) {
  29750. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29751. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29752. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29753. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29754. }
  29755. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29756. };
  29757. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29758. this._currentEffect.setFloat(name, x);
  29759. };
  29760. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29761. UniformBuffer._tempBuffer[0] = x;
  29762. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29763. };
  29764. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29765. if (suffix === void 0) { suffix = ""; }
  29766. this._currentEffect.setFloat2(name + suffix, x, y);
  29767. };
  29768. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29769. if (suffix === void 0) { suffix = ""; }
  29770. UniformBuffer._tempBuffer[0] = x;
  29771. UniformBuffer._tempBuffer[1] = y;
  29772. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29773. };
  29774. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29775. if (suffix === void 0) { suffix = ""; }
  29776. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29777. };
  29778. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29779. if (suffix === void 0) { suffix = ""; }
  29780. UniformBuffer._tempBuffer[0] = x;
  29781. UniformBuffer._tempBuffer[1] = y;
  29782. UniformBuffer._tempBuffer[2] = z;
  29783. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29784. };
  29785. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29786. if (suffix === void 0) { suffix = ""; }
  29787. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29788. };
  29789. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29790. if (suffix === void 0) { suffix = ""; }
  29791. UniformBuffer._tempBuffer[0] = x;
  29792. UniformBuffer._tempBuffer[1] = y;
  29793. UniformBuffer._tempBuffer[2] = z;
  29794. UniformBuffer._tempBuffer[3] = w;
  29795. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29796. };
  29797. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29798. this._currentEffect.setMatrix(name, mat);
  29799. };
  29800. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29801. this.updateUniform(name, mat.toArray(), 16);
  29802. };
  29803. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29804. this._currentEffect.setVector3(name, vector);
  29805. };
  29806. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29807. vector.toArray(UniformBuffer._tempBuffer);
  29808. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29809. };
  29810. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29811. this._currentEffect.setVector4(name, vector);
  29812. };
  29813. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29814. vector.toArray(UniformBuffer._tempBuffer);
  29815. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29816. };
  29817. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29818. if (suffix === void 0) { suffix = ""; }
  29819. this._currentEffect.setColor3(name + suffix, color);
  29820. };
  29821. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29822. if (suffix === void 0) { suffix = ""; }
  29823. color.toArray(UniformBuffer._tempBuffer);
  29824. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29825. };
  29826. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29827. if (suffix === void 0) { suffix = ""; }
  29828. this._currentEffect.setColor4(name + suffix, color, alpha);
  29829. };
  29830. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29831. if (suffix === void 0) { suffix = ""; }
  29832. color.toArray(UniformBuffer._tempBuffer);
  29833. UniformBuffer._tempBuffer[3] = alpha;
  29834. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29835. };
  29836. /**
  29837. * Sets a sampler uniform on the effect.
  29838. * @param {string} name Name of the sampler.
  29839. * @param {Texture} texture
  29840. */
  29841. UniformBuffer.prototype.setTexture = function (name, texture) {
  29842. this._currentEffect.setTexture(name, texture);
  29843. };
  29844. /**
  29845. * Directly updates the value of the uniform in the cache AND on the GPU.
  29846. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29847. * @param {number[]|Float32Array} data Flattened data
  29848. */
  29849. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29850. this.updateUniform(uniformName, data, data.length);
  29851. this.update();
  29852. };
  29853. /**
  29854. * Binds this uniform buffer to an effect.
  29855. * @param {Effect} effect
  29856. * @param {string} name Name of the uniform block in the shader.
  29857. */
  29858. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29859. this._currentEffect = effect;
  29860. if (this._noUBO || !this._buffer) {
  29861. return;
  29862. }
  29863. effect.bindUniformBuffer(this._buffer, name);
  29864. };
  29865. /**
  29866. * Disposes the uniform buffer.
  29867. */
  29868. UniformBuffer.prototype.dispose = function () {
  29869. if (this._noUBO) {
  29870. return;
  29871. }
  29872. var index = this._engine._uniformBuffers.indexOf(this);
  29873. if (index !== -1) {
  29874. this._engine._uniformBuffers.splice(index, 1);
  29875. }
  29876. if (!this._buffer) {
  29877. return;
  29878. }
  29879. if (this._engine._releaseBuffer(this._buffer)) {
  29880. this._buffer = null;
  29881. }
  29882. };
  29883. // Pool for avoiding memory leaks
  29884. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29885. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29886. return UniformBuffer;
  29887. }());
  29888. BABYLON.UniformBuffer = UniformBuffer;
  29889. })(BABYLON || (BABYLON = {}));
  29890. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29891. var BABYLON;
  29892. (function (BABYLON) {
  29893. var VertexData = /** @class */ (function () {
  29894. function VertexData() {
  29895. }
  29896. VertexData.prototype.set = function (data, kind) {
  29897. switch (kind) {
  29898. case BABYLON.VertexBuffer.PositionKind:
  29899. this.positions = data;
  29900. break;
  29901. case BABYLON.VertexBuffer.NormalKind:
  29902. this.normals = data;
  29903. break;
  29904. case BABYLON.VertexBuffer.TangentKind:
  29905. this.tangents = data;
  29906. break;
  29907. case BABYLON.VertexBuffer.UVKind:
  29908. this.uvs = data;
  29909. break;
  29910. case BABYLON.VertexBuffer.UV2Kind:
  29911. this.uvs2 = data;
  29912. break;
  29913. case BABYLON.VertexBuffer.UV3Kind:
  29914. this.uvs3 = data;
  29915. break;
  29916. case BABYLON.VertexBuffer.UV4Kind:
  29917. this.uvs4 = data;
  29918. break;
  29919. case BABYLON.VertexBuffer.UV5Kind:
  29920. this.uvs5 = data;
  29921. break;
  29922. case BABYLON.VertexBuffer.UV6Kind:
  29923. this.uvs6 = data;
  29924. break;
  29925. case BABYLON.VertexBuffer.ColorKind:
  29926. this.colors = data;
  29927. break;
  29928. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29929. this.matricesIndices = data;
  29930. break;
  29931. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29932. this.matricesWeights = data;
  29933. break;
  29934. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29935. this.matricesIndicesExtra = data;
  29936. break;
  29937. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29938. this.matricesWeightsExtra = data;
  29939. break;
  29940. }
  29941. };
  29942. /**
  29943. * Associates the vertexData to the passed Mesh.
  29944. * Sets it as updatable or not (default `false`).
  29945. * Returns the VertexData.
  29946. */
  29947. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29948. this._applyTo(mesh, updatable);
  29949. return this;
  29950. };
  29951. /**
  29952. * Associates the vertexData to the passed Geometry.
  29953. * Sets it as updatable or not (default `false`).
  29954. * Returns the VertexData.
  29955. */
  29956. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29957. this._applyTo(geometry, updatable);
  29958. return this;
  29959. };
  29960. /**
  29961. * Updates the associated mesh.
  29962. * Returns the VertexData.
  29963. */
  29964. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29965. this._update(mesh);
  29966. return this;
  29967. };
  29968. /**
  29969. * Updates the associated geometry.
  29970. * Returns the VertexData.
  29971. */
  29972. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29973. this._update(geometry);
  29974. return this;
  29975. };
  29976. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29977. if (updatable === void 0) { updatable = false; }
  29978. if (this.positions) {
  29979. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29980. }
  29981. if (this.normals) {
  29982. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29983. }
  29984. if (this.tangents) {
  29985. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29986. }
  29987. if (this.uvs) {
  29988. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29989. }
  29990. if (this.uvs2) {
  29991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29992. }
  29993. if (this.uvs3) {
  29994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29995. }
  29996. if (this.uvs4) {
  29997. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29998. }
  29999. if (this.uvs5) {
  30000. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30001. }
  30002. if (this.uvs6) {
  30003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30004. }
  30005. if (this.colors) {
  30006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30007. }
  30008. if (this.matricesIndices) {
  30009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30010. }
  30011. if (this.matricesWeights) {
  30012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30013. }
  30014. if (this.matricesIndicesExtra) {
  30015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30016. }
  30017. if (this.matricesWeightsExtra) {
  30018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30019. }
  30020. if (this.indices) {
  30021. meshOrGeometry.setIndices(this.indices, null, updatable);
  30022. }
  30023. return this;
  30024. };
  30025. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30026. if (this.positions) {
  30027. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30028. }
  30029. if (this.normals) {
  30030. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30031. }
  30032. if (this.tangents) {
  30033. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30034. }
  30035. if (this.uvs) {
  30036. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30037. }
  30038. if (this.uvs2) {
  30039. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30040. }
  30041. if (this.uvs3) {
  30042. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30043. }
  30044. if (this.uvs4) {
  30045. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30046. }
  30047. if (this.uvs5) {
  30048. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30049. }
  30050. if (this.uvs6) {
  30051. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30052. }
  30053. if (this.colors) {
  30054. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30055. }
  30056. if (this.matricesIndices) {
  30057. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30058. }
  30059. if (this.matricesWeights) {
  30060. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30061. }
  30062. if (this.matricesIndicesExtra) {
  30063. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30064. }
  30065. if (this.matricesWeightsExtra) {
  30066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30067. }
  30068. if (this.indices) {
  30069. meshOrGeometry.setIndices(this.indices, null);
  30070. }
  30071. return this;
  30072. };
  30073. /**
  30074. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30075. * Returns the VertexData.
  30076. */
  30077. VertexData.prototype.transform = function (matrix) {
  30078. var transformed = BABYLON.Vector3.Zero();
  30079. var index;
  30080. if (this.positions) {
  30081. var position = BABYLON.Vector3.Zero();
  30082. for (index = 0; index < this.positions.length; index += 3) {
  30083. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30084. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30085. this.positions[index] = transformed.x;
  30086. this.positions[index + 1] = transformed.y;
  30087. this.positions[index + 2] = transformed.z;
  30088. }
  30089. }
  30090. if (this.normals) {
  30091. var normal = BABYLON.Vector3.Zero();
  30092. for (index = 0; index < this.normals.length; index += 3) {
  30093. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30094. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30095. this.normals[index] = transformed.x;
  30096. this.normals[index + 1] = transformed.y;
  30097. this.normals[index + 2] = transformed.z;
  30098. }
  30099. }
  30100. if (this.tangents) {
  30101. var tangent = BABYLON.Vector4.Zero();
  30102. var tangentTransformed = BABYLON.Vector4.Zero();
  30103. for (index = 0; index < this.tangents.length; index += 4) {
  30104. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30105. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30106. this.tangents[index] = tangentTransformed.x;
  30107. this.tangents[index + 1] = tangentTransformed.y;
  30108. this.tangents[index + 2] = tangentTransformed.z;
  30109. this.tangents[index + 3] = tangentTransformed.w;
  30110. }
  30111. }
  30112. return this;
  30113. };
  30114. /**
  30115. * Merges the passed VertexData into the current one.
  30116. * Returns the modified VertexData.
  30117. */
  30118. VertexData.prototype.merge = function (other, options) {
  30119. options = options || {};
  30120. if (other.indices) {
  30121. if (!this.indices) {
  30122. this.indices = [];
  30123. }
  30124. var offset = this.positions ? this.positions.length / 3 : 0;
  30125. for (var index = 0; index < other.indices.length; index++) {
  30126. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30127. this.indices.push(other.indices[index] + offset);
  30128. }
  30129. }
  30130. this.positions = this._mergeElement(this.positions, other.positions);
  30131. if (!this.positions) {
  30132. return this;
  30133. }
  30134. var count = this.positions.length / 3;
  30135. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30136. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30137. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30138. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30139. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30140. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30141. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30142. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30143. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30144. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30145. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30146. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30147. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30148. return this;
  30149. };
  30150. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30151. if (length === void 0) { length = 0; }
  30152. if (defaultValue === void 0) { defaultValue = 0; }
  30153. if (!other && !source) {
  30154. return null;
  30155. }
  30156. if (!other) {
  30157. var padding = new Float32Array(source.length);
  30158. padding.fill(defaultValue);
  30159. return this._mergeElement(source, padding, length);
  30160. }
  30161. if (!source) {
  30162. if (length === 0 || length === other.length) {
  30163. return other;
  30164. }
  30165. var padding = new Float32Array(length - other.length);
  30166. padding.fill(defaultValue);
  30167. return this._mergeElement(padding, other, length);
  30168. }
  30169. var len = other.length + source.length;
  30170. var isSrcTypedArray = source instanceof Float32Array;
  30171. var isOthTypedArray = other instanceof Float32Array;
  30172. // use non-loop method when the source is Float32Array
  30173. if (isSrcTypedArray) {
  30174. var ret32 = new Float32Array(len);
  30175. ret32.set(source);
  30176. ret32.set(other, source.length);
  30177. return ret32;
  30178. // source is number[], when other is also use concat
  30179. }
  30180. else if (!isOthTypedArray) {
  30181. return source.concat(other);
  30182. // source is a number[], but other is a Float32Array, loop required
  30183. }
  30184. else {
  30185. var ret = source.slice(0); // copy source to a separate array
  30186. for (var i = 0, len = other.length; i < len; i++) {
  30187. ret.push(other[i]);
  30188. }
  30189. return ret;
  30190. }
  30191. };
  30192. /**
  30193. * Serializes the VertexData.
  30194. * Returns a serialized object.
  30195. */
  30196. VertexData.prototype.serialize = function () {
  30197. var serializationObject = this.serialize();
  30198. if (this.positions) {
  30199. serializationObject.positions = this.positions;
  30200. }
  30201. if (this.normals) {
  30202. serializationObject.normals = this.normals;
  30203. }
  30204. if (this.tangents) {
  30205. serializationObject.tangents = this.tangents;
  30206. }
  30207. if (this.uvs) {
  30208. serializationObject.uvs = this.uvs;
  30209. }
  30210. if (this.uvs2) {
  30211. serializationObject.uvs2 = this.uvs2;
  30212. }
  30213. if (this.uvs3) {
  30214. serializationObject.uvs3 = this.uvs3;
  30215. }
  30216. if (this.uvs4) {
  30217. serializationObject.uvs4 = this.uvs4;
  30218. }
  30219. if (this.uvs5) {
  30220. serializationObject.uvs5 = this.uvs5;
  30221. }
  30222. if (this.uvs6) {
  30223. serializationObject.uvs6 = this.uvs6;
  30224. }
  30225. if (this.colors) {
  30226. serializationObject.colors = this.colors;
  30227. }
  30228. if (this.matricesIndices) {
  30229. serializationObject.matricesIndices = this.matricesIndices;
  30230. serializationObject.matricesIndices._isExpanded = true;
  30231. }
  30232. if (this.matricesWeights) {
  30233. serializationObject.matricesWeights = this.matricesWeights;
  30234. }
  30235. if (this.matricesIndicesExtra) {
  30236. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30237. serializationObject.matricesIndicesExtra._isExpanded = true;
  30238. }
  30239. if (this.matricesWeightsExtra) {
  30240. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30241. }
  30242. serializationObject.indices = this.indices;
  30243. return serializationObject;
  30244. };
  30245. // Statics
  30246. /**
  30247. * Returns the object VertexData associated to the passed mesh.
  30248. */
  30249. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30250. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30251. };
  30252. /**
  30253. * Returns the object VertexData associated to the passed geometry.
  30254. */
  30255. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30256. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30257. };
  30258. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30259. var result = new VertexData();
  30260. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30261. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30262. }
  30263. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30264. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30265. }
  30266. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30267. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30268. }
  30269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30270. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30271. }
  30272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30273. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30274. }
  30275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30276. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30277. }
  30278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30279. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30280. }
  30281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30282. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30283. }
  30284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30285. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30286. }
  30287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30288. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30289. }
  30290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30291. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30292. }
  30293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30294. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30295. }
  30296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30297. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30298. }
  30299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30300. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30301. }
  30302. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30303. return result;
  30304. };
  30305. /**
  30306. * Creates the vertexData of the Ribbon.
  30307. */
  30308. VertexData.CreateRibbon = function (options) {
  30309. var pathArray = options.pathArray;
  30310. var closeArray = options.closeArray || false;
  30311. var closePath = options.closePath || false;
  30312. var invertUV = options.invertUV || false;
  30313. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30314. var offset = options.offset || defaultOffset;
  30315. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30317. var customUV = options.uvs;
  30318. var customColors = options.colors;
  30319. var positions = [];
  30320. var indices = [];
  30321. var normals = [];
  30322. var uvs = [];
  30323. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30324. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30325. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30326. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30327. var minlg; // minimal length among all paths from pathArray
  30328. var lg = []; // array of path lengths : nb of vertex per path
  30329. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30330. var p; // path iterator
  30331. var i; // point iterator
  30332. var j; // point iterator
  30333. // if single path in pathArray
  30334. if (pathArray.length < 2) {
  30335. var ar1 = [];
  30336. var ar2 = [];
  30337. for (i = 0; i < pathArray[0].length - offset; i++) {
  30338. ar1.push(pathArray[0][i]);
  30339. ar2.push(pathArray[0][i + offset]);
  30340. }
  30341. pathArray = [ar1, ar2];
  30342. }
  30343. // positions and horizontal distances (u)
  30344. var idc = 0;
  30345. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30346. var path;
  30347. var l;
  30348. minlg = pathArray[0].length;
  30349. var vectlg;
  30350. var dist;
  30351. for (p = 0; p < pathArray.length; p++) {
  30352. uTotalDistance[p] = 0;
  30353. us[p] = [0];
  30354. path = pathArray[p];
  30355. l = path.length;
  30356. minlg = (minlg < l) ? minlg : l;
  30357. j = 0;
  30358. while (j < l) {
  30359. positions.push(path[j].x, path[j].y, path[j].z);
  30360. if (j > 0) {
  30361. vectlg = path[j].subtract(path[j - 1]).length();
  30362. dist = vectlg + uTotalDistance[p];
  30363. us[p].push(dist);
  30364. uTotalDistance[p] = dist;
  30365. }
  30366. j++;
  30367. }
  30368. if (closePath) {
  30369. j--;
  30370. positions.push(path[0].x, path[0].y, path[0].z);
  30371. vectlg = path[j].subtract(path[0]).length();
  30372. dist = vectlg + uTotalDistance[p];
  30373. us[p].push(dist);
  30374. uTotalDistance[p] = dist;
  30375. }
  30376. lg[p] = l + closePathCorr;
  30377. idx[p] = idc;
  30378. idc += (l + closePathCorr);
  30379. }
  30380. // vertical distances (v)
  30381. var path1;
  30382. var path2;
  30383. var vertex1 = null;
  30384. var vertex2 = null;
  30385. for (i = 0; i < minlg + closePathCorr; i++) {
  30386. vTotalDistance[i] = 0;
  30387. vs[i] = [0];
  30388. for (p = 0; p < pathArray.length - 1; p++) {
  30389. path1 = pathArray[p];
  30390. path2 = pathArray[p + 1];
  30391. if (i === minlg) {
  30392. vertex1 = path1[0];
  30393. vertex2 = path2[0];
  30394. }
  30395. else {
  30396. vertex1 = path1[i];
  30397. vertex2 = path2[i];
  30398. }
  30399. vectlg = vertex2.subtract(vertex1).length();
  30400. dist = vectlg + vTotalDistance[i];
  30401. vs[i].push(dist);
  30402. vTotalDistance[i] = dist;
  30403. }
  30404. if (closeArray && vertex2 && vertex1) {
  30405. path1 = pathArray[p];
  30406. path2 = pathArray[0];
  30407. if (i === minlg) {
  30408. vertex2 = path2[0];
  30409. }
  30410. vectlg = vertex2.subtract(vertex1).length();
  30411. dist = vectlg + vTotalDistance[i];
  30412. vTotalDistance[i] = dist;
  30413. }
  30414. }
  30415. // uvs
  30416. var u;
  30417. var v;
  30418. if (customUV) {
  30419. for (p = 0; p < customUV.length; p++) {
  30420. uvs.push(customUV[p].x, customUV[p].y);
  30421. }
  30422. }
  30423. else {
  30424. for (p = 0; p < pathArray.length; p++) {
  30425. for (i = 0; i < minlg + closePathCorr; i++) {
  30426. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30427. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30428. if (invertUV) {
  30429. uvs.push(v, u);
  30430. }
  30431. else {
  30432. uvs.push(u, v);
  30433. }
  30434. }
  30435. }
  30436. }
  30437. // indices
  30438. p = 0; // path index
  30439. var pi = 0; // positions array index
  30440. var l1 = lg[p] - 1; // path1 length
  30441. var l2 = lg[p + 1] - 1; // path2 length
  30442. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30443. var shft = idx[1] - idx[0]; // shift
  30444. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30445. while (pi <= min && p < path1nb) {
  30446. // 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
  30447. indices.push(pi, pi + shft, pi + 1);
  30448. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30449. pi += 1;
  30450. if (pi === min) {
  30451. p++;
  30452. if (p === lg.length - 1) {
  30453. shft = idx[0] - idx[p];
  30454. l1 = lg[p] - 1;
  30455. l2 = lg[0] - 1;
  30456. }
  30457. else {
  30458. shft = idx[p + 1] - idx[p];
  30459. l1 = lg[p] - 1;
  30460. l2 = lg[p + 1] - 1;
  30461. }
  30462. pi = idx[p];
  30463. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30464. }
  30465. }
  30466. // normals
  30467. VertexData.ComputeNormals(positions, indices, normals);
  30468. if (closePath) {
  30469. var indexFirst = 0;
  30470. var indexLast = 0;
  30471. for (p = 0; p < pathArray.length; p++) {
  30472. indexFirst = idx[p] * 3;
  30473. if (p + 1 < pathArray.length) {
  30474. indexLast = (idx[p + 1] - 1) * 3;
  30475. }
  30476. else {
  30477. indexLast = normals.length - 3;
  30478. }
  30479. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30480. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30481. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30482. normals[indexLast] = normals[indexFirst];
  30483. normals[indexLast + 1] = normals[indexFirst + 1];
  30484. normals[indexLast + 2] = normals[indexFirst + 2];
  30485. }
  30486. }
  30487. // sides
  30488. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30489. // Colors
  30490. var colors = null;
  30491. if (customColors) {
  30492. colors = new Float32Array(customColors.length * 4);
  30493. for (var c = 0; c < customColors.length; c++) {
  30494. colors[c * 4] = customColors[c].r;
  30495. colors[c * 4 + 1] = customColors[c].g;
  30496. colors[c * 4 + 2] = customColors[c].b;
  30497. colors[c * 4 + 3] = customColors[c].a;
  30498. }
  30499. }
  30500. // Result
  30501. var vertexData = new VertexData();
  30502. var positions32 = new Float32Array(positions);
  30503. var normals32 = new Float32Array(normals);
  30504. var uvs32 = new Float32Array(uvs);
  30505. vertexData.indices = indices;
  30506. vertexData.positions = positions32;
  30507. vertexData.normals = normals32;
  30508. vertexData.uvs = uvs32;
  30509. if (colors) {
  30510. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30511. }
  30512. if (closePath) {
  30513. vertexData._idx = idx;
  30514. }
  30515. return vertexData;
  30516. };
  30517. /**
  30518. * Creates the VertexData of the Box.
  30519. */
  30520. VertexData.CreateBox = function (options) {
  30521. var normalsSource = [
  30522. new BABYLON.Vector3(0, 0, 1),
  30523. new BABYLON.Vector3(0, 0, -1),
  30524. new BABYLON.Vector3(1, 0, 0),
  30525. new BABYLON.Vector3(-1, 0, 0),
  30526. new BABYLON.Vector3(0, 1, 0),
  30527. new BABYLON.Vector3(0, -1, 0)
  30528. ];
  30529. var indices = [];
  30530. var positions = [];
  30531. var normals = [];
  30532. var uvs = [];
  30533. var width = options.width || options.size || 1;
  30534. var height = options.height || options.size || 1;
  30535. var depth = options.depth || options.size || 1;
  30536. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30537. var faceUV = options.faceUV || new Array(6);
  30538. var faceColors = options.faceColors;
  30539. var colors = [];
  30540. // default face colors and UV if undefined
  30541. for (var f = 0; f < 6; f++) {
  30542. if (faceUV[f] === undefined) {
  30543. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30544. }
  30545. if (faceColors && faceColors[f] === undefined) {
  30546. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30547. }
  30548. }
  30549. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30550. // Create each face in turn.
  30551. for (var index = 0; index < normalsSource.length; index++) {
  30552. var normal = normalsSource[index];
  30553. // Get two vectors perpendicular to the face normal and to each other.
  30554. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30555. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30556. // Six indices (two triangles) per face.
  30557. var verticesLength = positions.length / 3;
  30558. indices.push(verticesLength);
  30559. indices.push(verticesLength + 1);
  30560. indices.push(verticesLength + 2);
  30561. indices.push(verticesLength);
  30562. indices.push(verticesLength + 2);
  30563. indices.push(verticesLength + 3);
  30564. // Four vertices per face.
  30565. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30566. positions.push(vertex.x, vertex.y, vertex.z);
  30567. normals.push(normal.x, normal.y, normal.z);
  30568. uvs.push(faceUV[index].z, faceUV[index].w);
  30569. if (faceColors) {
  30570. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30571. }
  30572. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30573. positions.push(vertex.x, vertex.y, vertex.z);
  30574. normals.push(normal.x, normal.y, normal.z);
  30575. uvs.push(faceUV[index].x, faceUV[index].w);
  30576. if (faceColors) {
  30577. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30578. }
  30579. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30580. positions.push(vertex.x, vertex.y, vertex.z);
  30581. normals.push(normal.x, normal.y, normal.z);
  30582. uvs.push(faceUV[index].x, faceUV[index].y);
  30583. if (faceColors) {
  30584. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30585. }
  30586. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30587. positions.push(vertex.x, vertex.y, vertex.z);
  30588. normals.push(normal.x, normal.y, normal.z);
  30589. uvs.push(faceUV[index].z, faceUV[index].y);
  30590. if (faceColors) {
  30591. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30592. }
  30593. }
  30594. // sides
  30595. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30596. // Result
  30597. var vertexData = new VertexData();
  30598. vertexData.indices = indices;
  30599. vertexData.positions = positions;
  30600. vertexData.normals = normals;
  30601. vertexData.uvs = uvs;
  30602. if (faceColors) {
  30603. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30604. vertexData.colors = totalColors;
  30605. }
  30606. return vertexData;
  30607. };
  30608. /**
  30609. * Creates the VertexData of the Sphere.
  30610. */
  30611. VertexData.CreateSphere = function (options) {
  30612. var segments = options.segments || 32;
  30613. var diameterX = options.diameterX || options.diameter || 1;
  30614. var diameterY = options.diameterY || options.diameter || 1;
  30615. var diameterZ = options.diameterZ || options.diameter || 1;
  30616. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30617. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30618. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30619. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30620. var totalZRotationSteps = 2 + segments;
  30621. var totalYRotationSteps = 2 * totalZRotationSteps;
  30622. var indices = [];
  30623. var positions = [];
  30624. var normals = [];
  30625. var uvs = [];
  30626. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30627. var normalizedZ = zRotationStep / totalZRotationSteps;
  30628. var angleZ = normalizedZ * Math.PI * slice;
  30629. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30630. var normalizedY = yRotationStep / totalYRotationSteps;
  30631. var angleY = normalizedY * Math.PI * 2 * arc;
  30632. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30633. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30634. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30635. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30636. var vertex = complete.multiply(radius);
  30637. var normal = complete.divide(radius).normalize();
  30638. positions.push(vertex.x, vertex.y, vertex.z);
  30639. normals.push(normal.x, normal.y, normal.z);
  30640. uvs.push(normalizedY, normalizedZ);
  30641. }
  30642. if (zRotationStep > 0) {
  30643. var verticesCount = positions.length / 3;
  30644. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30645. indices.push((firstIndex));
  30646. indices.push((firstIndex + 1));
  30647. indices.push(firstIndex + totalYRotationSteps + 1);
  30648. indices.push((firstIndex + totalYRotationSteps + 1));
  30649. indices.push((firstIndex + 1));
  30650. indices.push((firstIndex + totalYRotationSteps + 2));
  30651. }
  30652. }
  30653. }
  30654. // Sides
  30655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30656. // Result
  30657. var vertexData = new VertexData();
  30658. vertexData.indices = indices;
  30659. vertexData.positions = positions;
  30660. vertexData.normals = normals;
  30661. vertexData.uvs = uvs;
  30662. return vertexData;
  30663. };
  30664. /**
  30665. * Creates the VertexData of the Cylinder or Cone.
  30666. */
  30667. VertexData.CreateCylinder = function (options) {
  30668. var height = options.height || 2;
  30669. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30670. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30671. var tessellation = options.tessellation || 24;
  30672. var subdivisions = options.subdivisions || 1;
  30673. var hasRings = options.hasRings ? true : false;
  30674. var enclose = options.enclose ? true : false;
  30675. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30677. var faceUV = options.faceUV || new Array(3);
  30678. var faceColors = options.faceColors;
  30679. // default face colors and UV if undefined
  30680. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30681. var ringNb = (hasRings) ? subdivisions : 1;
  30682. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30683. var f;
  30684. for (f = 0; f < surfaceNb; f++) {
  30685. if (faceColors && faceColors[f] === undefined) {
  30686. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30687. }
  30688. }
  30689. for (f = 0; f < surfaceNb; f++) {
  30690. if (faceUV && faceUV[f] === undefined) {
  30691. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30692. }
  30693. }
  30694. var indices = new Array();
  30695. var positions = new Array();
  30696. var normals = new Array();
  30697. var uvs = new Array();
  30698. var colors = new Array();
  30699. var angle_step = Math.PI * 2 * arc / tessellation;
  30700. var angle;
  30701. var h;
  30702. var radius;
  30703. var tan = (diameterBottom - diameterTop) / 2 / height;
  30704. var ringVertex = BABYLON.Vector3.Zero();
  30705. var ringNormal = BABYLON.Vector3.Zero();
  30706. var ringFirstVertex = BABYLON.Vector3.Zero();
  30707. var ringFirstNormal = BABYLON.Vector3.Zero();
  30708. var quadNormal = BABYLON.Vector3.Zero();
  30709. var Y = BABYLON.Axis.Y;
  30710. // positions, normals, uvs
  30711. var i;
  30712. var j;
  30713. var r;
  30714. var ringIdx = 1;
  30715. var s = 1; // surface index
  30716. var cs = 0;
  30717. var v = 0;
  30718. for (i = 0; i <= subdivisions; i++) {
  30719. h = i / subdivisions;
  30720. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30721. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30722. for (r = 0; r < ringIdx; r++) {
  30723. if (hasRings) {
  30724. s += r;
  30725. }
  30726. if (enclose) {
  30727. s += 2 * r;
  30728. }
  30729. for (j = 0; j <= tessellation; j++) {
  30730. angle = j * angle_step;
  30731. // position
  30732. ringVertex.x = Math.cos(-angle) * radius;
  30733. ringVertex.y = -height / 2 + h * height;
  30734. ringVertex.z = Math.sin(-angle) * radius;
  30735. // normal
  30736. if (diameterTop === 0 && i === subdivisions) {
  30737. // if no top cap, reuse former normals
  30738. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30739. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30740. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30741. }
  30742. else {
  30743. ringNormal.x = ringVertex.x;
  30744. ringNormal.z = ringVertex.z;
  30745. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30746. ringNormal.normalize();
  30747. }
  30748. // keep first ring vertex values for enclose
  30749. if (j === 0) {
  30750. ringFirstVertex.copyFrom(ringVertex);
  30751. ringFirstNormal.copyFrom(ringNormal);
  30752. }
  30753. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30754. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30755. if (hasRings) {
  30756. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30757. }
  30758. else {
  30759. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30760. }
  30761. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30762. if (faceColors) {
  30763. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30764. }
  30765. }
  30766. // if enclose, add four vertices and their dedicated normals
  30767. if (arc !== 1 && enclose) {
  30768. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30769. positions.push(0, ringVertex.y, 0);
  30770. positions.push(0, ringVertex.y, 0);
  30771. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30772. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30773. quadNormal.normalize();
  30774. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30775. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30776. quadNormal.normalize();
  30777. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30778. if (hasRings) {
  30779. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30780. }
  30781. else {
  30782. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30783. }
  30784. uvs.push(faceUV[s + 1].x, v);
  30785. uvs.push(faceUV[s + 1].z, v);
  30786. if (hasRings) {
  30787. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30788. }
  30789. else {
  30790. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30791. }
  30792. uvs.push(faceUV[s + 2].x, v);
  30793. uvs.push(faceUV[s + 2].z, v);
  30794. if (faceColors) {
  30795. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30796. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30797. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30798. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30799. }
  30800. }
  30801. if (cs !== s) {
  30802. cs = s;
  30803. }
  30804. }
  30805. }
  30806. // indices
  30807. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30808. var s;
  30809. i = 0;
  30810. for (s = 0; s < subdivisions; s++) {
  30811. var i0 = 0;
  30812. var i1 = 0;
  30813. var i2 = 0;
  30814. var i3 = 0;
  30815. for (j = 0; j < tessellation; j++) {
  30816. i0 = i * (e + 1) + j;
  30817. i1 = (i + 1) * (e + 1) + j;
  30818. i2 = i * (e + 1) + (j + 1);
  30819. i3 = (i + 1) * (e + 1) + (j + 1);
  30820. indices.push(i0, i1, i2);
  30821. indices.push(i3, i2, i1);
  30822. }
  30823. if (arc !== 1 && enclose) {
  30824. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30825. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30826. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30827. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30828. }
  30829. i = (hasRings) ? (i + 2) : (i + 1);
  30830. }
  30831. // Caps
  30832. var createCylinderCap = function (isTop) {
  30833. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30834. if (radius === 0) {
  30835. return;
  30836. }
  30837. // Cap positions, normals & uvs
  30838. var angle;
  30839. var circleVector;
  30840. var i;
  30841. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30842. var c = null;
  30843. if (faceColors) {
  30844. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30845. }
  30846. // cap center
  30847. var vbase = positions.length / 3;
  30848. var offset = isTop ? height / 2 : -height / 2;
  30849. var center = new BABYLON.Vector3(0, offset, 0);
  30850. positions.push(center.x, center.y, center.z);
  30851. normals.push(0, isTop ? 1 : -1, 0);
  30852. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30853. if (c) {
  30854. colors.push(c.r, c.g, c.b, c.a);
  30855. }
  30856. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30857. for (i = 0; i <= tessellation; i++) {
  30858. angle = Math.PI * 2 * i * arc / tessellation;
  30859. var cos = Math.cos(-angle);
  30860. var sin = Math.sin(-angle);
  30861. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30862. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30863. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30864. normals.push(0, isTop ? 1 : -1, 0);
  30865. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30866. if (c) {
  30867. colors.push(c.r, c.g, c.b, c.a);
  30868. }
  30869. }
  30870. // Cap indices
  30871. for (i = 0; i < tessellation; i++) {
  30872. if (!isTop) {
  30873. indices.push(vbase);
  30874. indices.push(vbase + (i + 1));
  30875. indices.push(vbase + (i + 2));
  30876. }
  30877. else {
  30878. indices.push(vbase);
  30879. indices.push(vbase + (i + 2));
  30880. indices.push(vbase + (i + 1));
  30881. }
  30882. }
  30883. };
  30884. // add caps to geometry
  30885. createCylinderCap(false);
  30886. createCylinderCap(true);
  30887. // Sides
  30888. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30889. var vertexData = new VertexData();
  30890. vertexData.indices = indices;
  30891. vertexData.positions = positions;
  30892. vertexData.normals = normals;
  30893. vertexData.uvs = uvs;
  30894. if (faceColors) {
  30895. vertexData.colors = colors;
  30896. }
  30897. return vertexData;
  30898. };
  30899. /**
  30900. * Creates the VertexData of the Torus.
  30901. */
  30902. VertexData.CreateTorus = function (options) {
  30903. var indices = [];
  30904. var positions = [];
  30905. var normals = [];
  30906. var uvs = [];
  30907. var diameter = options.diameter || 1;
  30908. var thickness = options.thickness || 0.5;
  30909. var tessellation = options.tessellation || 16;
  30910. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30911. var stride = tessellation + 1;
  30912. for (var i = 0; i <= tessellation; i++) {
  30913. var u = i / tessellation;
  30914. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30915. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30916. for (var j = 0; j <= tessellation; j++) {
  30917. var v = 1 - j / tessellation;
  30918. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30919. var dx = Math.cos(innerAngle);
  30920. var dy = Math.sin(innerAngle);
  30921. // Create a vertex.
  30922. var normal = new BABYLON.Vector3(dx, dy, 0);
  30923. var position = normal.scale(thickness / 2);
  30924. var textureCoordinate = new BABYLON.Vector2(u, v);
  30925. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30926. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30927. positions.push(position.x, position.y, position.z);
  30928. normals.push(normal.x, normal.y, normal.z);
  30929. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30930. // And create indices for two triangles.
  30931. var nextI = (i + 1) % stride;
  30932. var nextJ = (j + 1) % stride;
  30933. indices.push(i * stride + j);
  30934. indices.push(i * stride + nextJ);
  30935. indices.push(nextI * stride + j);
  30936. indices.push(i * stride + nextJ);
  30937. indices.push(nextI * stride + nextJ);
  30938. indices.push(nextI * stride + j);
  30939. }
  30940. }
  30941. // Sides
  30942. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30943. // Result
  30944. var vertexData = new VertexData();
  30945. vertexData.indices = indices;
  30946. vertexData.positions = positions;
  30947. vertexData.normals = normals;
  30948. vertexData.uvs = uvs;
  30949. return vertexData;
  30950. };
  30951. /**
  30952. * Creates the VertexData of the LineSystem.
  30953. */
  30954. VertexData.CreateLineSystem = function (options) {
  30955. var indices = [];
  30956. var positions = [];
  30957. var lines = options.lines;
  30958. var colors = options.colors;
  30959. var vertexColors = [];
  30960. var idx = 0;
  30961. for (var l = 0; l < lines.length; l++) {
  30962. var points = lines[l];
  30963. for (var index = 0; index < points.length; index++) {
  30964. positions.push(points[index].x, points[index].y, points[index].z);
  30965. if (colors) {
  30966. var color = colors[l];
  30967. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30968. }
  30969. if (index > 0) {
  30970. indices.push(idx - 1);
  30971. indices.push(idx);
  30972. }
  30973. idx++;
  30974. }
  30975. }
  30976. var vertexData = new VertexData();
  30977. vertexData.indices = indices;
  30978. vertexData.positions = positions;
  30979. if (colors) {
  30980. vertexData.colors = vertexColors;
  30981. }
  30982. return vertexData;
  30983. };
  30984. /**
  30985. * Create the VertexData of the DashedLines.
  30986. */
  30987. VertexData.CreateDashedLines = function (options) {
  30988. var dashSize = options.dashSize || 3;
  30989. var gapSize = options.gapSize || 1;
  30990. var dashNb = options.dashNb || 200;
  30991. var points = options.points;
  30992. var positions = new Array();
  30993. var indices = new Array();
  30994. var curvect = BABYLON.Vector3.Zero();
  30995. var lg = 0;
  30996. var nb = 0;
  30997. var shft = 0;
  30998. var dashshft = 0;
  30999. var curshft = 0;
  31000. var idx = 0;
  31001. var i = 0;
  31002. for (i = 0; i < points.length - 1; i++) {
  31003. points[i + 1].subtractToRef(points[i], curvect);
  31004. lg += curvect.length();
  31005. }
  31006. shft = lg / dashNb;
  31007. dashshft = dashSize * shft / (dashSize + gapSize);
  31008. for (i = 0; i < points.length - 1; i++) {
  31009. points[i + 1].subtractToRef(points[i], curvect);
  31010. nb = Math.floor(curvect.length() / shft);
  31011. curvect.normalize();
  31012. for (var j = 0; j < nb; j++) {
  31013. curshft = shft * j;
  31014. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31015. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31016. indices.push(idx, idx + 1);
  31017. idx += 2;
  31018. }
  31019. }
  31020. // Result
  31021. var vertexData = new VertexData();
  31022. vertexData.positions = positions;
  31023. vertexData.indices = indices;
  31024. return vertexData;
  31025. };
  31026. /**
  31027. * Creates the VertexData of the Ground.
  31028. */
  31029. VertexData.CreateGround = function (options) {
  31030. var indices = [];
  31031. var positions = [];
  31032. var normals = [];
  31033. var uvs = [];
  31034. var row, col;
  31035. var width = options.width || 1;
  31036. var height = options.height || 1;
  31037. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31038. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31039. for (row = 0; row <= subdivisionsY; row++) {
  31040. for (col = 0; col <= subdivisionsX; col++) {
  31041. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31042. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31043. positions.push(position.x, position.y, position.z);
  31044. normals.push(normal.x, normal.y, normal.z);
  31045. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31046. }
  31047. }
  31048. for (row = 0; row < subdivisionsY; row++) {
  31049. for (col = 0; col < subdivisionsX; col++) {
  31050. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31051. indices.push(col + 1 + row * (subdivisionsX + 1));
  31052. indices.push(col + row * (subdivisionsX + 1));
  31053. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31054. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31055. indices.push(col + row * (subdivisionsX + 1));
  31056. }
  31057. }
  31058. // Result
  31059. var vertexData = new VertexData();
  31060. vertexData.indices = indices;
  31061. vertexData.positions = positions;
  31062. vertexData.normals = normals;
  31063. vertexData.uvs = uvs;
  31064. return vertexData;
  31065. };
  31066. /**
  31067. * Creates the VertexData of the TiledGround.
  31068. */
  31069. VertexData.CreateTiledGround = function (options) {
  31070. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31071. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31072. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31073. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31074. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31075. var precision = options.precision || { w: 1, h: 1 };
  31076. var indices = new Array();
  31077. var positions = new Array();
  31078. var normals = new Array();
  31079. var uvs = new Array();
  31080. var row, col, tileRow, tileCol;
  31081. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31082. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31083. precision.w = (precision.w < 1) ? 1 : precision.w;
  31084. precision.h = (precision.h < 1) ? 1 : precision.h;
  31085. var tileSize = {
  31086. 'w': (xmax - xmin) / subdivisions.w,
  31087. 'h': (zmax - zmin) / subdivisions.h
  31088. };
  31089. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31090. // Indices
  31091. var base = positions.length / 3;
  31092. var rowLength = precision.w + 1;
  31093. for (row = 0; row < precision.h; row++) {
  31094. for (col = 0; col < precision.w; col++) {
  31095. var square = [
  31096. base + col + row * rowLength,
  31097. base + (col + 1) + row * rowLength,
  31098. base + (col + 1) + (row + 1) * rowLength,
  31099. base + col + (row + 1) * rowLength
  31100. ];
  31101. indices.push(square[1]);
  31102. indices.push(square[2]);
  31103. indices.push(square[3]);
  31104. indices.push(square[0]);
  31105. indices.push(square[1]);
  31106. indices.push(square[3]);
  31107. }
  31108. }
  31109. // Position, normals and uvs
  31110. var position = BABYLON.Vector3.Zero();
  31111. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31112. for (row = 0; row <= precision.h; row++) {
  31113. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31114. for (col = 0; col <= precision.w; col++) {
  31115. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31116. position.y = 0;
  31117. positions.push(position.x, position.y, position.z);
  31118. normals.push(normal.x, normal.y, normal.z);
  31119. uvs.push(col / precision.w, row / precision.h);
  31120. }
  31121. }
  31122. }
  31123. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31124. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31125. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31126. }
  31127. }
  31128. // Result
  31129. var vertexData = new VertexData();
  31130. vertexData.indices = indices;
  31131. vertexData.positions = positions;
  31132. vertexData.normals = normals;
  31133. vertexData.uvs = uvs;
  31134. return vertexData;
  31135. };
  31136. /**
  31137. * Creates the VertexData of the Ground designed from a heightmap.
  31138. */
  31139. VertexData.CreateGroundFromHeightMap = function (options) {
  31140. var indices = [];
  31141. var positions = [];
  31142. var normals = [];
  31143. var uvs = [];
  31144. var row, col;
  31145. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31146. // Vertices
  31147. for (row = 0; row <= options.subdivisions; row++) {
  31148. for (col = 0; col <= options.subdivisions; col++) {
  31149. 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));
  31150. // Compute height
  31151. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31152. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31153. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31154. var r = options.buffer[pos] / 255.0;
  31155. var g = options.buffer[pos + 1] / 255.0;
  31156. var b = options.buffer[pos + 2] / 255.0;
  31157. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31158. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31159. // Add vertex
  31160. positions.push(position.x, position.y, position.z);
  31161. normals.push(0, 0, 0);
  31162. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31163. }
  31164. }
  31165. // Indices
  31166. for (row = 0; row < options.subdivisions; row++) {
  31167. for (col = 0; col < options.subdivisions; col++) {
  31168. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31169. indices.push(col + 1 + row * (options.subdivisions + 1));
  31170. indices.push(col + row * (options.subdivisions + 1));
  31171. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31172. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31173. indices.push(col + row * (options.subdivisions + 1));
  31174. }
  31175. }
  31176. // Normals
  31177. VertexData.ComputeNormals(positions, indices, normals);
  31178. // Result
  31179. var vertexData = new VertexData();
  31180. vertexData.indices = indices;
  31181. vertexData.positions = positions;
  31182. vertexData.normals = normals;
  31183. vertexData.uvs = uvs;
  31184. return vertexData;
  31185. };
  31186. /**
  31187. * Creates the VertexData of the Plane.
  31188. */
  31189. VertexData.CreatePlane = function (options) {
  31190. var indices = [];
  31191. var positions = [];
  31192. var normals = [];
  31193. var uvs = [];
  31194. var width = options.width || options.size || 1;
  31195. var height = options.height || options.size || 1;
  31196. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31197. // Vertices
  31198. var halfWidth = width / 2.0;
  31199. var halfHeight = height / 2.0;
  31200. positions.push(-halfWidth, -halfHeight, 0);
  31201. normals.push(0, 0, -1.0);
  31202. uvs.push(0.0, 0.0);
  31203. positions.push(halfWidth, -halfHeight, 0);
  31204. normals.push(0, 0, -1.0);
  31205. uvs.push(1.0, 0.0);
  31206. positions.push(halfWidth, halfHeight, 0);
  31207. normals.push(0, 0, -1.0);
  31208. uvs.push(1.0, 1.0);
  31209. positions.push(-halfWidth, halfHeight, 0);
  31210. normals.push(0, 0, -1.0);
  31211. uvs.push(0.0, 1.0);
  31212. // Indices
  31213. indices.push(0);
  31214. indices.push(1);
  31215. indices.push(2);
  31216. indices.push(0);
  31217. indices.push(2);
  31218. indices.push(3);
  31219. // Sides
  31220. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31221. // Result
  31222. var vertexData = new VertexData();
  31223. vertexData.indices = indices;
  31224. vertexData.positions = positions;
  31225. vertexData.normals = normals;
  31226. vertexData.uvs = uvs;
  31227. return vertexData;
  31228. };
  31229. /**
  31230. * Creates the VertexData of the Disc or regular Polygon.
  31231. */
  31232. VertexData.CreateDisc = function (options) {
  31233. var positions = new Array();
  31234. var indices = new Array();
  31235. var normals = new Array();
  31236. var uvs = new Array();
  31237. var radius = options.radius || 0.5;
  31238. var tessellation = options.tessellation || 64;
  31239. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31240. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31241. // positions and uvs
  31242. positions.push(0, 0, 0); // disc center first
  31243. uvs.push(0.5, 0.5);
  31244. var theta = Math.PI * 2 * arc;
  31245. var step = theta / tessellation;
  31246. for (var a = 0; a < theta; a += step) {
  31247. var x = Math.cos(a);
  31248. var y = Math.sin(a);
  31249. var u = (x + 1) / 2;
  31250. var v = (1 - y) / 2;
  31251. positions.push(radius * x, radius * y, 0);
  31252. uvs.push(u, v);
  31253. }
  31254. if (arc === 1) {
  31255. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31256. uvs.push(uvs[2], uvs[3]);
  31257. }
  31258. //indices
  31259. var vertexNb = positions.length / 3;
  31260. for (var i = 1; i < vertexNb - 1; i++) {
  31261. indices.push(i + 1, 0, i);
  31262. }
  31263. // result
  31264. VertexData.ComputeNormals(positions, indices, normals);
  31265. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31266. var vertexData = new VertexData();
  31267. vertexData.indices = indices;
  31268. vertexData.positions = positions;
  31269. vertexData.normals = normals;
  31270. vertexData.uvs = uvs;
  31271. return vertexData;
  31272. };
  31273. /**
  31274. * Re-creates the VertexData of the Polygon for sideOrientation.
  31275. */
  31276. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31277. var faceUV = fUV || new Array(3);
  31278. var faceColors = fColors;
  31279. var colors = [];
  31280. // default face colors and UV if undefined
  31281. for (var f = 0; f < 3; f++) {
  31282. if (faceUV[f] === undefined) {
  31283. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31284. }
  31285. if (faceColors && faceColors[f] === undefined) {
  31286. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31287. }
  31288. }
  31289. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31290. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31291. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31292. var indices = polygon.getIndices();
  31293. // set face colours and textures
  31294. var idx = 0;
  31295. var face = 0;
  31296. for (var index = 0; index < normals.length; index += 3) {
  31297. //Edge Face no. 1
  31298. if (Math.abs(normals[index + 1]) < 0.001) {
  31299. face = 1;
  31300. }
  31301. //Top Face no. 0
  31302. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31303. face = 0;
  31304. }
  31305. //Bottom Face no. 2
  31306. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31307. face = 2;
  31308. }
  31309. idx = index / 3;
  31310. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31311. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31312. if (faceColors) {
  31313. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31314. }
  31315. }
  31316. // sides
  31317. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31318. // Result
  31319. var vertexData = new VertexData();
  31320. vertexData.indices = indices;
  31321. vertexData.positions = positions;
  31322. vertexData.normals = normals;
  31323. vertexData.uvs = uvs;
  31324. if (faceColors) {
  31325. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31326. vertexData.colors = totalColors;
  31327. }
  31328. return vertexData;
  31329. };
  31330. /**
  31331. * Creates the VertexData of the IcoSphere.
  31332. */
  31333. VertexData.CreateIcoSphere = function (options) {
  31334. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31335. var radius = options.radius || 1;
  31336. var flat = (options.flat === undefined) ? true : options.flat;
  31337. var subdivisions = options.subdivisions || 4;
  31338. var radiusX = options.radiusX || radius;
  31339. var radiusY = options.radiusY || radius;
  31340. var radiusZ = options.radiusZ || radius;
  31341. var t = (1 + Math.sqrt(5)) / 2;
  31342. // 12 vertex x,y,z
  31343. var ico_vertices = [
  31344. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31345. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31346. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31347. ];
  31348. // index of 3 vertex makes a face of icopshere
  31349. var ico_indices = [
  31350. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31351. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31352. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31353. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31354. ];
  31355. // vertex for uv have aliased position, not for UV
  31356. var vertices_unalias_id = [
  31357. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31358. // vertex alias
  31359. 0,
  31360. 2,
  31361. 3,
  31362. 3,
  31363. 3,
  31364. 4,
  31365. 7,
  31366. 8,
  31367. 9,
  31368. 9,
  31369. 10,
  31370. 11 // 23: B + 12
  31371. ];
  31372. // uv as integer step (not pixels !)
  31373. var ico_vertexuv = [
  31374. 5, 1, 3, 1, 6, 4, 0, 0,
  31375. 5, 3, 4, 2, 2, 2, 4, 0,
  31376. 2, 0, 1, 1, 6, 0, 6, 2,
  31377. // vertex alias (for same vertex on different faces)
  31378. 0, 4,
  31379. 3, 3,
  31380. 4, 4,
  31381. 3, 1,
  31382. 4, 2,
  31383. 4, 4,
  31384. 0, 2,
  31385. 1, 1,
  31386. 2, 2,
  31387. 3, 3,
  31388. 1, 3,
  31389. 2, 4 // 23: B + 12
  31390. ];
  31391. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31392. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31393. // First island of uv mapping
  31394. // v = 4h 3+ 2
  31395. // v = 3h 9+ 4
  31396. // v = 2h 9+ 5 B
  31397. // v = 1h 9 1 0
  31398. // v = 0h 3 8 7 A
  31399. // u = 0 1 2 3 4 5 6 *a
  31400. // Second island of uv mapping
  31401. // v = 4h 0+ B+ 4+
  31402. // v = 3h A+ 2+
  31403. // v = 2h 7+ 6 3+
  31404. // v = 1h 8+ 3+
  31405. // v = 0h
  31406. // u = 0 1 2 3 4 5 6 *a
  31407. // Face layout on texture UV mapping
  31408. // ============
  31409. // \ 4 /\ 16 / ======
  31410. // \ / \ / /\ 11 /
  31411. // \/ 7 \/ / \ /
  31412. // ======= / 10 \/
  31413. // /\ 17 /\ =======
  31414. // / \ / \ \ 15 /\
  31415. // / 8 \/ 12 \ \ / \
  31416. // ============ \/ 6 \
  31417. // \ 18 /\ ============
  31418. // \ / \ \ 5 /\ 0 /
  31419. // \/ 13 \ \ / \ /
  31420. // ======= \/ 1 \/
  31421. // =============
  31422. // /\ 19 /\ 2 /\
  31423. // / \ / \ / \
  31424. // / 14 \/ 9 \/ 3 \
  31425. // ===================
  31426. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31427. var ustep = 138 / 1024;
  31428. var vstep = 239 / 1024;
  31429. var uoffset = 60 / 1024;
  31430. var voffset = 26 / 1024;
  31431. // Second island should have margin, not to touch the first island
  31432. // avoid any borderline artefact in pixel rounding
  31433. var island_u_offset = -40 / 1024;
  31434. var island_v_offset = +20 / 1024;
  31435. // face is either island 0 or 1 :
  31436. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31437. var island = [
  31438. 0, 0, 0, 0, 1,
  31439. 0, 0, 1, 1, 0,
  31440. 0, 0, 1, 1, 0,
  31441. 0, 1, 1, 1, 0 // 15 - 19
  31442. ];
  31443. var indices = new Array();
  31444. var positions = new Array();
  31445. var normals = new Array();
  31446. var uvs = new Array();
  31447. var current_indice = 0;
  31448. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31449. var face_vertex_pos = new Array(3);
  31450. var face_vertex_uv = new Array(3);
  31451. var v012;
  31452. for (v012 = 0; v012 < 3; v012++) {
  31453. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31454. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31455. }
  31456. // create all with normals
  31457. for (var face = 0; face < 20; face++) {
  31458. // 3 vertex per face
  31459. for (v012 = 0; v012 < 3; v012++) {
  31460. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31461. var v_id = ico_indices[3 * face + v012];
  31462. // vertex have 3D position (x,y,z)
  31463. 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]);
  31464. // Normalize to get normal, then scale to radius
  31465. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31466. // uv Coordinates from vertex ID
  31467. 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);
  31468. }
  31469. // Subdivide the face (interpolate pos, norm, uv)
  31470. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31471. // - norm is linear interpolation of vertex corner normal
  31472. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31473. // - uv is linear interpolation
  31474. //
  31475. // Topology is as below for sub-divide by 2
  31476. // vertex shown as v0,v1,v2
  31477. // interp index is i1 to progress in range [v0,v1[
  31478. // interp index is i2 to progress in range [v0,v2[
  31479. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31480. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31481. //
  31482. //
  31483. // i2 v2
  31484. // ^ ^
  31485. // / / \
  31486. // / / \
  31487. // / / \
  31488. // / / (0,1) \
  31489. // / #---------\
  31490. // / / \ (0,0)'/ \
  31491. // / / \ / \
  31492. // / / \ / \
  31493. // / / (0,0) \ / (1,0) \
  31494. // / #---------#---------\
  31495. // v0 v1
  31496. //
  31497. // --------------------> i1
  31498. //
  31499. // interp of (i1,i2):
  31500. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31501. // along i1 : lerp(x0,x1, i1/(S-i2))
  31502. //
  31503. // centroid of triangle is needed to get help normal computation
  31504. // (c1,c2) are used for centroid location
  31505. var interp_vertex = function (i1, i2, c1, c2) {
  31506. // vertex is interpolated from
  31507. // - face_vertex_pos[0..2]
  31508. // - face_vertex_uv[0..2]
  31509. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31510. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31511. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31512. pos_interp.normalize();
  31513. var vertex_normal;
  31514. if (flat) {
  31515. // in flat mode, recalculate normal as face centroid normal
  31516. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31517. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31518. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31519. }
  31520. else {
  31521. // in smooth mode, recalculate normal from each single vertex position
  31522. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31523. }
  31524. // Vertex normal need correction due to X,Y,Z radius scaling
  31525. vertex_normal.x /= radiusX;
  31526. vertex_normal.y /= radiusY;
  31527. vertex_normal.z /= radiusZ;
  31528. vertex_normal.normalize();
  31529. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31530. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31531. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31532. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31533. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31534. uvs.push(uv_interp.x, uv_interp.y);
  31535. // push each vertex has member of a face
  31536. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31537. indices.push(current_indice);
  31538. current_indice++;
  31539. };
  31540. for (var i2 = 0; i2 < subdivisions; i2++) {
  31541. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31542. // face : (i1,i2) for /\ :
  31543. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31544. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31545. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31546. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31547. if (i1 + i2 + 1 < subdivisions) {
  31548. // face : (i1,i2)' for \/ :
  31549. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31550. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31551. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31552. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31553. }
  31554. }
  31555. }
  31556. }
  31557. // Sides
  31558. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31559. // Result
  31560. var vertexData = new VertexData();
  31561. vertexData.indices = indices;
  31562. vertexData.positions = positions;
  31563. vertexData.normals = normals;
  31564. vertexData.uvs = uvs;
  31565. return vertexData;
  31566. };
  31567. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31568. /**
  31569. * Creates the VertexData of the Polyhedron.
  31570. */
  31571. VertexData.CreatePolyhedron = function (options) {
  31572. // provided polyhedron types :
  31573. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31574. // 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)
  31575. var polyhedra = [];
  31576. 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]] };
  31577. 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]] };
  31578. polyhedra[2] = {
  31579. 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]],
  31580. 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]]
  31581. };
  31582. polyhedra[3] = {
  31583. 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]],
  31584. 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]]
  31585. };
  31586. polyhedra[4] = {
  31587. 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]],
  31588. 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]]
  31589. };
  31590. 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]] };
  31591. 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]] };
  31592. 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]] };
  31593. 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]] };
  31594. 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]] };
  31595. 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]] };
  31596. 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]] };
  31597. 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]] };
  31598. 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]] };
  31599. polyhedra[14] = {
  31600. 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]],
  31601. 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]]
  31602. };
  31603. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31604. var size = options.size;
  31605. var sizeX = options.sizeX || size || 1;
  31606. var sizeY = options.sizeY || size || 1;
  31607. var sizeZ = options.sizeZ || size || 1;
  31608. var data = options.custom || polyhedra[type];
  31609. var nbfaces = data.face.length;
  31610. var faceUV = options.faceUV || new Array(nbfaces);
  31611. var faceColors = options.faceColors;
  31612. var flat = (options.flat === undefined) ? true : options.flat;
  31613. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31614. var positions = new Array();
  31615. var indices = new Array();
  31616. var normals = new Array();
  31617. var uvs = new Array();
  31618. var colors = new Array();
  31619. var index = 0;
  31620. var faceIdx = 0; // face cursor in the array "indexes"
  31621. var indexes = new Array();
  31622. var i = 0;
  31623. var f = 0;
  31624. var u, v, ang, x, y, tmp;
  31625. // default face colors and UV if undefined
  31626. if (flat) {
  31627. for (f = 0; f < nbfaces; f++) {
  31628. if (faceColors && faceColors[f] === undefined) {
  31629. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31630. }
  31631. if (faceUV && faceUV[f] === undefined) {
  31632. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31633. }
  31634. }
  31635. }
  31636. if (!flat) {
  31637. for (i = 0; i < data.vertex.length; i++) {
  31638. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31639. uvs.push(0, 0);
  31640. }
  31641. for (f = 0; f < nbfaces; f++) {
  31642. for (i = 0; i < data.face[f].length - 2; i++) {
  31643. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31644. }
  31645. }
  31646. }
  31647. else {
  31648. for (f = 0; f < nbfaces; f++) {
  31649. var fl = data.face[f].length; // number of vertices of the current face
  31650. ang = 2 * Math.PI / fl;
  31651. x = 0.5 * Math.tan(ang / 2);
  31652. y = 0.5;
  31653. // positions, uvs, colors
  31654. for (i = 0; i < fl; i++) {
  31655. // positions
  31656. 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);
  31657. indexes.push(index);
  31658. index++;
  31659. // uvs
  31660. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31661. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31662. uvs.push(u, v);
  31663. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31664. y = x * Math.sin(ang) + y * Math.cos(ang);
  31665. x = tmp;
  31666. // colors
  31667. if (faceColors) {
  31668. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31669. }
  31670. }
  31671. // indices from indexes
  31672. for (i = 0; i < fl - 2; i++) {
  31673. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31674. }
  31675. faceIdx += fl;
  31676. }
  31677. }
  31678. VertexData.ComputeNormals(positions, indices, normals);
  31679. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31680. var vertexData = new VertexData();
  31681. vertexData.positions = positions;
  31682. vertexData.indices = indices;
  31683. vertexData.normals = normals;
  31684. vertexData.uvs = uvs;
  31685. if (faceColors && flat) {
  31686. vertexData.colors = colors;
  31687. }
  31688. return vertexData;
  31689. };
  31690. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31691. /**
  31692. * Creates the VertexData of the Torus Knot.
  31693. */
  31694. VertexData.CreateTorusKnot = function (options) {
  31695. var indices = new Array();
  31696. var positions = new Array();
  31697. var normals = new Array();
  31698. var uvs = new Array();
  31699. var radius = options.radius || 2;
  31700. var tube = options.tube || 0.5;
  31701. var radialSegments = options.radialSegments || 32;
  31702. var tubularSegments = options.tubularSegments || 32;
  31703. var p = options.p || 2;
  31704. var q = options.q || 3;
  31705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31706. // Helper
  31707. var getPos = function (angle) {
  31708. var cu = Math.cos(angle);
  31709. var su = Math.sin(angle);
  31710. var quOverP = q / p * angle;
  31711. var cs = Math.cos(quOverP);
  31712. var tx = radius * (2 + cs) * 0.5 * cu;
  31713. var ty = radius * (2 + cs) * su * 0.5;
  31714. var tz = radius * Math.sin(quOverP) * 0.5;
  31715. return new BABYLON.Vector3(tx, ty, tz);
  31716. };
  31717. // Vertices
  31718. var i;
  31719. var j;
  31720. for (i = 0; i <= radialSegments; i++) {
  31721. var modI = i % radialSegments;
  31722. var u = modI / radialSegments * 2 * p * Math.PI;
  31723. var p1 = getPos(u);
  31724. var p2 = getPos(u + 0.01);
  31725. var tang = p2.subtract(p1);
  31726. var n = p2.add(p1);
  31727. var bitan = BABYLON.Vector3.Cross(tang, n);
  31728. n = BABYLON.Vector3.Cross(bitan, tang);
  31729. bitan.normalize();
  31730. n.normalize();
  31731. for (j = 0; j < tubularSegments; j++) {
  31732. var modJ = j % tubularSegments;
  31733. var v = modJ / tubularSegments * 2 * Math.PI;
  31734. var cx = -tube * Math.cos(v);
  31735. var cy = tube * Math.sin(v);
  31736. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31737. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31738. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31739. uvs.push(i / radialSegments);
  31740. uvs.push(j / tubularSegments);
  31741. }
  31742. }
  31743. for (i = 0; i < radialSegments; i++) {
  31744. for (j = 0; j < tubularSegments; j++) {
  31745. var jNext = (j + 1) % tubularSegments;
  31746. var a = i * tubularSegments + j;
  31747. var b = (i + 1) * tubularSegments + j;
  31748. var c = (i + 1) * tubularSegments + jNext;
  31749. var d = i * tubularSegments + jNext;
  31750. indices.push(d);
  31751. indices.push(b);
  31752. indices.push(a);
  31753. indices.push(d);
  31754. indices.push(c);
  31755. indices.push(b);
  31756. }
  31757. }
  31758. // Normals
  31759. VertexData.ComputeNormals(positions, indices, normals);
  31760. // Sides
  31761. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31762. // Result
  31763. var vertexData = new VertexData();
  31764. vertexData.indices = indices;
  31765. vertexData.positions = positions;
  31766. vertexData.normals = normals;
  31767. vertexData.uvs = uvs;
  31768. return vertexData;
  31769. };
  31770. // Tools
  31771. /**
  31772. * @param {any} - positions (number[] or Float32Array)
  31773. * @param {any} - indices (number[] or Uint16Array)
  31774. * @param {any} - normals (number[] or Float32Array)
  31775. * options (optional) :
  31776. * facetPositions : optional array of facet positions (vector3)
  31777. * facetNormals : optional array of facet normals (vector3)
  31778. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31779. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31780. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31781. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31782. * bInfo : optional bounding info, required for facetPartitioning computation
  31783. * useRightHandedSystem: optional boolean to for right handed system computation
  31784. * depthSort : optional boolean to enable the facet depth sort computation
  31785. * distanceTo : optional Vector3 to compute the facet depth from this location
  31786. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31787. */
  31788. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31789. // temporary scalar variables
  31790. var index = 0; // facet index
  31791. var p1p2x = 0.0; // p1p2 vector x coordinate
  31792. var p1p2y = 0.0; // p1p2 vector y coordinate
  31793. var p1p2z = 0.0; // p1p2 vector z coordinate
  31794. var p3p2x = 0.0; // p3p2 vector x coordinate
  31795. var p3p2y = 0.0; // p3p2 vector y coordinate
  31796. var p3p2z = 0.0; // p3p2 vector z coordinate
  31797. var faceNormalx = 0.0; // facet normal x coordinate
  31798. var faceNormaly = 0.0; // facet normal y coordinate
  31799. var faceNormalz = 0.0; // facet normal z coordinate
  31800. var length = 0.0; // facet normal length before normalization
  31801. var v1x = 0; // vector1 x index in the positions array
  31802. var v1y = 0; // vector1 y index in the positions array
  31803. var v1z = 0; // vector1 z index in the positions array
  31804. var v2x = 0; // vector2 x index in the positions array
  31805. var v2y = 0; // vector2 y index in the positions array
  31806. var v2z = 0; // vector2 z index in the positions array
  31807. var v3x = 0; // vector3 x index in the positions array
  31808. var v3y = 0; // vector3 y index in the positions array
  31809. var v3z = 0; // vector3 z index in the positions array
  31810. var computeFacetNormals = false;
  31811. var computeFacetPositions = false;
  31812. var computeFacetPartitioning = false;
  31813. var computeDepthSort = false;
  31814. var faceNormalSign = 1;
  31815. var ratio = 0;
  31816. var distanceTo = null;
  31817. if (options) {
  31818. computeFacetNormals = (options.facetNormals) ? true : false;
  31819. computeFacetPositions = (options.facetPositions) ? true : false;
  31820. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31821. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31822. ratio = options.ratio || 0;
  31823. computeDepthSort = (options.depthSort) ? true : false;
  31824. distanceTo = (options.distanceTo);
  31825. if (computeDepthSort) {
  31826. if (distanceTo === undefined) {
  31827. distanceTo = BABYLON.Vector3.Zero();
  31828. }
  31829. var depthSortedFacets = options.depthSortedFacets;
  31830. }
  31831. }
  31832. // facetPartitioning reinit if needed
  31833. var xSubRatio = 0;
  31834. var ySubRatio = 0;
  31835. var zSubRatio = 0;
  31836. var subSq = 0;
  31837. if (computeFacetPartitioning && options && options.bbSize) {
  31838. var ox = 0; // X partitioning index for facet position
  31839. var oy = 0; // Y partinioning index for facet position
  31840. var oz = 0; // Z partinioning index for facet position
  31841. var b1x = 0; // X partitioning index for facet v1 vertex
  31842. var b1y = 0; // Y partitioning index for facet v1 vertex
  31843. var b1z = 0; // z partitioning index for facet v1 vertex
  31844. var b2x = 0; // X partitioning index for facet v2 vertex
  31845. var b2y = 0; // Y partitioning index for facet v2 vertex
  31846. var b2z = 0; // Z partitioning index for facet v2 vertex
  31847. var b3x = 0; // X partitioning index for facet v3 vertex
  31848. var b3y = 0; // Y partitioning index for facet v3 vertex
  31849. var b3z = 0; // Z partitioning index for facet v3 vertex
  31850. var block_idx_o = 0; // facet barycenter block index
  31851. var block_idx_v1 = 0; // v1 vertex block index
  31852. var block_idx_v2 = 0; // v2 vertex block index
  31853. var block_idx_v3 = 0; // v3 vertex block index
  31854. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31855. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31856. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31857. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31858. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31859. subSq = options.subDiv.max * options.subDiv.max;
  31860. options.facetPartitioning.length = 0;
  31861. }
  31862. // reset the normals
  31863. for (index = 0; index < positions.length; index++) {
  31864. normals[index] = 0.0;
  31865. }
  31866. // Loop : 1 indice triplet = 1 facet
  31867. var nbFaces = (indices.length / 3) | 0;
  31868. for (index = 0; index < nbFaces; index++) {
  31869. // get the indexes of the coordinates of each vertex of the facet
  31870. v1x = indices[index * 3] * 3;
  31871. v1y = v1x + 1;
  31872. v1z = v1x + 2;
  31873. v2x = indices[index * 3 + 1] * 3;
  31874. v2y = v2x + 1;
  31875. v2z = v2x + 2;
  31876. v3x = indices[index * 3 + 2] * 3;
  31877. v3y = v3x + 1;
  31878. v3z = v3x + 2;
  31879. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31880. p1p2y = positions[v1y] - positions[v2y];
  31881. p1p2z = positions[v1z] - positions[v2z];
  31882. p3p2x = positions[v3x] - positions[v2x];
  31883. p3p2y = positions[v3y] - positions[v2y];
  31884. p3p2z = positions[v3z] - positions[v2z];
  31885. // compute the face normal with the cross product
  31886. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31887. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31888. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31889. // normalize this normal and store it in the array facetData
  31890. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31891. length = (length === 0) ? 1.0 : length;
  31892. faceNormalx /= length;
  31893. faceNormaly /= length;
  31894. faceNormalz /= length;
  31895. if (computeFacetNormals && options) {
  31896. options.facetNormals[index].x = faceNormalx;
  31897. options.facetNormals[index].y = faceNormaly;
  31898. options.facetNormals[index].z = faceNormalz;
  31899. }
  31900. if (computeFacetPositions && options) {
  31901. // compute and the facet barycenter coordinates in the array facetPositions
  31902. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31903. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31904. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31905. }
  31906. if (computeFacetPartitioning && options) {
  31907. // store the facet indexes in arrays in the main facetPartitioning array :
  31908. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31909. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31910. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31911. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31912. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31913. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31914. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31915. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31916. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31917. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31918. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31919. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31920. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31921. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31922. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31923. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31924. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31925. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31926. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31927. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31928. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31929. // push each facet index in each block containing the vertex
  31930. options.facetPartitioning[block_idx_v1].push(index);
  31931. if (block_idx_v2 != block_idx_v1) {
  31932. options.facetPartitioning[block_idx_v2].push(index);
  31933. }
  31934. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31935. options.facetPartitioning[block_idx_v3].push(index);
  31936. }
  31937. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31938. options.facetPartitioning[block_idx_o].push(index);
  31939. }
  31940. }
  31941. if (computeDepthSort && options && options.facetPositions) {
  31942. var dsf = depthSortedFacets[index];
  31943. dsf.ind = index * 3;
  31944. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31945. }
  31946. // compute the normals anyway
  31947. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31948. normals[v1y] += faceNormaly;
  31949. normals[v1z] += faceNormalz;
  31950. normals[v2x] += faceNormalx;
  31951. normals[v2y] += faceNormaly;
  31952. normals[v2z] += faceNormalz;
  31953. normals[v3x] += faceNormalx;
  31954. normals[v3y] += faceNormaly;
  31955. normals[v3z] += faceNormalz;
  31956. }
  31957. // last normalization of each normal
  31958. for (index = 0; index < normals.length / 3; index++) {
  31959. faceNormalx = normals[index * 3];
  31960. faceNormaly = normals[index * 3 + 1];
  31961. faceNormalz = normals[index * 3 + 2];
  31962. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31963. length = (length === 0) ? 1.0 : length;
  31964. faceNormalx /= length;
  31965. faceNormaly /= length;
  31966. faceNormalz /= length;
  31967. normals[index * 3] = faceNormalx;
  31968. normals[index * 3 + 1] = faceNormaly;
  31969. normals[index * 3 + 2] = faceNormalz;
  31970. }
  31971. };
  31972. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31973. var li = indices.length;
  31974. var ln = normals.length;
  31975. var i;
  31976. var n;
  31977. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31978. switch (sideOrientation) {
  31979. case BABYLON.Mesh.FRONTSIDE:
  31980. // nothing changed
  31981. break;
  31982. case BABYLON.Mesh.BACKSIDE:
  31983. var tmp;
  31984. // indices
  31985. for (i = 0; i < li; i += 3) {
  31986. tmp = indices[i];
  31987. indices[i] = indices[i + 2];
  31988. indices[i + 2] = tmp;
  31989. }
  31990. // normals
  31991. for (n = 0; n < ln; n++) {
  31992. normals[n] = -normals[n];
  31993. }
  31994. break;
  31995. case BABYLON.Mesh.DOUBLESIDE:
  31996. // positions
  31997. var lp = positions.length;
  31998. var l = lp / 3;
  31999. for (var p = 0; p < lp; p++) {
  32000. positions[lp + p] = positions[p];
  32001. }
  32002. // indices
  32003. for (i = 0; i < li; i += 3) {
  32004. indices[i + li] = indices[i + 2] + l;
  32005. indices[i + 1 + li] = indices[i + 1] + l;
  32006. indices[i + 2 + li] = indices[i] + l;
  32007. }
  32008. // normals
  32009. for (n = 0; n < ln; n++) {
  32010. normals[ln + n] = -normals[n];
  32011. }
  32012. // uvs
  32013. var lu = uvs.length;
  32014. var u = 0;
  32015. for (u = 0; u < lu; u++) {
  32016. uvs[u + lu] = uvs[u];
  32017. }
  32018. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32019. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32020. u = 0;
  32021. for (i = 0; i < lu / 2; i++) {
  32022. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32023. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32024. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32025. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32026. u += 2;
  32027. }
  32028. break;
  32029. }
  32030. };
  32031. /**
  32032. * Creates a new VertexData from the imported parameters.
  32033. */
  32034. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32035. var vertexData = new VertexData();
  32036. // positions
  32037. var positions = parsedVertexData.positions;
  32038. if (positions) {
  32039. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32040. }
  32041. // normals
  32042. var normals = parsedVertexData.normals;
  32043. if (normals) {
  32044. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32045. }
  32046. // tangents
  32047. var tangents = parsedVertexData.tangents;
  32048. if (tangents) {
  32049. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32050. }
  32051. // uvs
  32052. var uvs = parsedVertexData.uvs;
  32053. if (uvs) {
  32054. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32055. }
  32056. // uv2s
  32057. var uv2s = parsedVertexData.uv2s;
  32058. if (uv2s) {
  32059. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32060. }
  32061. // uv3s
  32062. var uv3s = parsedVertexData.uv3s;
  32063. if (uv3s) {
  32064. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32065. }
  32066. // uv4s
  32067. var uv4s = parsedVertexData.uv4s;
  32068. if (uv4s) {
  32069. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32070. }
  32071. // uv5s
  32072. var uv5s = parsedVertexData.uv5s;
  32073. if (uv5s) {
  32074. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32075. }
  32076. // uv6s
  32077. var uv6s = parsedVertexData.uv6s;
  32078. if (uv6s) {
  32079. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32080. }
  32081. // colors
  32082. var colors = parsedVertexData.colors;
  32083. if (colors) {
  32084. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32085. }
  32086. // matricesIndices
  32087. var matricesIndices = parsedVertexData.matricesIndices;
  32088. if (matricesIndices) {
  32089. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32090. }
  32091. // matricesWeights
  32092. var matricesWeights = parsedVertexData.matricesWeights;
  32093. if (matricesWeights) {
  32094. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32095. }
  32096. // indices
  32097. var indices = parsedVertexData.indices;
  32098. if (indices) {
  32099. vertexData.indices = indices;
  32100. }
  32101. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32102. };
  32103. return VertexData;
  32104. }());
  32105. BABYLON.VertexData = VertexData;
  32106. })(BABYLON || (BABYLON = {}));
  32107. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32108. var BABYLON;
  32109. (function (BABYLON) {
  32110. /**
  32111. * Class used to store geometry data (vertex buffers + index buffer)
  32112. */
  32113. var Geometry = /** @class */ (function () {
  32114. /**
  32115. * Creates a new geometry
  32116. * @param id defines the unique ID
  32117. * @param scene defines the hosting scene
  32118. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32119. * @param updatable defines if geometry must be updatable (false by default)
  32120. * @param mesh defines the mesh that will be associated with the geometry
  32121. */
  32122. function Geometry(id, scene, vertexData, updatable, mesh) {
  32123. if (updatable === void 0) { updatable = false; }
  32124. if (mesh === void 0) { mesh = null; }
  32125. /**
  32126. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32127. */
  32128. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32129. this._totalVertices = 0;
  32130. this._isDisposed = false;
  32131. this._indexBufferIsUpdatable = false;
  32132. this.id = id;
  32133. this._engine = scene.getEngine();
  32134. this._meshes = [];
  32135. this._scene = scene;
  32136. //Init vertex buffer cache
  32137. this._vertexBuffers = {};
  32138. this._indices = [];
  32139. this._updatable = updatable;
  32140. // vertexData
  32141. if (vertexData) {
  32142. this.setAllVerticesData(vertexData, updatable);
  32143. }
  32144. else {
  32145. this._totalVertices = 0;
  32146. this._indices = [];
  32147. }
  32148. if (this._engine.getCaps().vertexArrayObject) {
  32149. this._vertexArrayObjects = {};
  32150. }
  32151. // applyToMesh
  32152. if (mesh) {
  32153. if (mesh.getClassName() === "LinesMesh") {
  32154. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32155. this.updateExtend();
  32156. }
  32157. this.applyToMesh(mesh);
  32158. mesh.computeWorldMatrix(true);
  32159. }
  32160. }
  32161. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32162. /**
  32163. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32164. */
  32165. get: function () {
  32166. return this._boundingBias;
  32167. },
  32168. /**
  32169. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  32170. */
  32171. set: function (value) {
  32172. if (this._boundingBias && this._boundingBias.equals(value)) {
  32173. return;
  32174. }
  32175. this._boundingBias = value.clone();
  32176. this.updateBoundingInfo(true, null);
  32177. },
  32178. enumerable: true,
  32179. configurable: true
  32180. });
  32181. /**
  32182. * Static function used to attach a new empty geometry to a mesh
  32183. * @param mesh defines the mesh to attach the geometry to
  32184. * @returns the new {BABYLON.Geometry}
  32185. */
  32186. Geometry.CreateGeometryForMesh = function (mesh) {
  32187. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32188. geometry.applyToMesh(mesh);
  32189. return geometry;
  32190. };
  32191. Object.defineProperty(Geometry.prototype, "extend", {
  32192. /**
  32193. * Gets the current extend of the geometry
  32194. */
  32195. get: function () {
  32196. return this._extend;
  32197. },
  32198. enumerable: true,
  32199. configurable: true
  32200. });
  32201. /**
  32202. * Gets the hosting scene
  32203. * @returns the hosting {BABYLON.Scene}
  32204. */
  32205. Geometry.prototype.getScene = function () {
  32206. return this._scene;
  32207. };
  32208. /**
  32209. * Gets the hosting engine
  32210. * @returns the hosting {BABYLON.Engine}
  32211. */
  32212. Geometry.prototype.getEngine = function () {
  32213. return this._engine;
  32214. };
  32215. /**
  32216. * Defines if the geometry is ready to use
  32217. * @returns true if the geometry is ready to be used
  32218. */
  32219. Geometry.prototype.isReady = function () {
  32220. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32221. };
  32222. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32223. /**
  32224. * Gets a value indicating that the geometry should not be serialized
  32225. */
  32226. get: function () {
  32227. for (var index = 0; index < this._meshes.length; index++) {
  32228. if (!this._meshes[index].doNotSerialize) {
  32229. return false;
  32230. }
  32231. }
  32232. return true;
  32233. },
  32234. enumerable: true,
  32235. configurable: true
  32236. });
  32237. /** @ignore */
  32238. Geometry.prototype._rebuild = function () {
  32239. if (this._vertexArrayObjects) {
  32240. this._vertexArrayObjects = {};
  32241. }
  32242. // Index buffer
  32243. if (this._meshes.length !== 0 && this._indices) {
  32244. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32245. }
  32246. // Vertex buffers
  32247. for (var key in this._vertexBuffers) {
  32248. var vertexBuffer = this._vertexBuffers[key];
  32249. vertexBuffer._rebuild();
  32250. }
  32251. };
  32252. /**
  32253. * Affects all gemetry data in one call
  32254. * @param vertexData defines the geometry data
  32255. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32256. */
  32257. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32258. vertexData.applyToGeometry(this, updatable);
  32259. this.notifyUpdate();
  32260. };
  32261. /**
  32262. * Set specific vertex data
  32263. * @param kind defines the data kind (Position, normal, etc...)
  32264. * @param data defines the vertex data to use
  32265. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32266. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32267. */
  32268. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32269. if (updatable === void 0) { updatable = false; }
  32270. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32271. this.setVerticesBuffer(buffer);
  32272. };
  32273. /**
  32274. * Removes a specific vertex data
  32275. * @param kind defines the data kind (Position, normal, etc...)
  32276. */
  32277. Geometry.prototype.removeVerticesData = function (kind) {
  32278. if (this._vertexBuffers[kind]) {
  32279. this._vertexBuffers[kind].dispose();
  32280. delete this._vertexBuffers[kind];
  32281. }
  32282. };
  32283. /**
  32284. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32285. * @param buffer defines the vertex buffer to use
  32286. */
  32287. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32288. var kind = buffer.getKind();
  32289. if (this._vertexBuffers[kind]) {
  32290. this._vertexBuffers[kind].dispose();
  32291. }
  32292. this._vertexBuffers[kind] = buffer;
  32293. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32294. var data = buffer.getData();
  32295. var stride = buffer.getStrideSize();
  32296. this._totalVertices = data.length / stride;
  32297. this.updateExtend(data, stride);
  32298. this._resetPointsArrayCache();
  32299. var meshes = this._meshes;
  32300. var numOfMeshes = meshes.length;
  32301. for (var index = 0; index < numOfMeshes; index++) {
  32302. var mesh = meshes[index];
  32303. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32304. mesh._createGlobalSubMesh(false);
  32305. mesh.computeWorldMatrix(true);
  32306. }
  32307. }
  32308. this.notifyUpdate(kind);
  32309. if (this._vertexArrayObjects) {
  32310. this._disposeVertexArrayObjects();
  32311. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32312. }
  32313. };
  32314. /**
  32315. * Update a specific vertex buffer
  32316. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32317. * It will do nothing if the buffer is not updatable
  32318. * @param kind defines the data kind (Position, normal, etc...)
  32319. * @param data defines the data to use
  32320. * @param offset defines the offset in the target buffer where to store the data
  32321. */
  32322. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32323. var vertexBuffer = this.getVertexBuffer(kind);
  32324. if (!vertexBuffer) {
  32325. return;
  32326. }
  32327. vertexBuffer.updateDirectly(data, offset);
  32328. this.notifyUpdate(kind);
  32329. };
  32330. /**
  32331. * Update a specific vertex buffer
  32332. * This function will create a new buffer if the current one is not updatable
  32333. * @param kind defines the data kind (Position, normal, etc...)
  32334. * @param data defines the data to use
  32335. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32336. */
  32337. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32338. if (updateExtends === void 0) { updateExtends = false; }
  32339. var vertexBuffer = this.getVertexBuffer(kind);
  32340. if (!vertexBuffer) {
  32341. return;
  32342. }
  32343. vertexBuffer.update(data);
  32344. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32345. var stride = vertexBuffer.getStrideSize();
  32346. this._totalVertices = data.length / stride;
  32347. this.updateBoundingInfo(updateExtends, data);
  32348. }
  32349. this.notifyUpdate(kind);
  32350. };
  32351. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32352. if (updateExtends) {
  32353. this.updateExtend(data);
  32354. }
  32355. var meshes = this._meshes;
  32356. var numOfMeshes = meshes.length;
  32357. this._resetPointsArrayCache();
  32358. for (var index = 0; index < numOfMeshes; index++) {
  32359. var mesh = meshes[index];
  32360. if (updateExtends) {
  32361. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32362. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32363. var subMesh = mesh.subMeshes[subIndex];
  32364. subMesh.refreshBoundingInfo();
  32365. }
  32366. }
  32367. }
  32368. };
  32369. /** @ignore */
  32370. Geometry.prototype._bind = function (effect, indexToBind) {
  32371. if (!effect) {
  32372. return;
  32373. }
  32374. if (indexToBind === undefined) {
  32375. indexToBind = this._indexBuffer;
  32376. }
  32377. var vbs = this.getVertexBuffers();
  32378. if (!vbs) {
  32379. return;
  32380. }
  32381. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32382. this._engine.bindBuffers(vbs, indexToBind, effect);
  32383. return;
  32384. }
  32385. // Using VAO
  32386. if (!this._vertexArrayObjects[effect.key]) {
  32387. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32388. }
  32389. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32390. };
  32391. /**
  32392. * Gets total number of vertices
  32393. * @returns the total number of vertices
  32394. */
  32395. Geometry.prototype.getTotalVertices = function () {
  32396. if (!this.isReady()) {
  32397. return 0;
  32398. }
  32399. return this._totalVertices;
  32400. };
  32401. /**
  32402. * Gets a specific vertex data attached to this geometry
  32403. * @param kind defines the data kind (Position, normal, etc...)
  32404. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32405. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32406. * @returns a float array containing vertex data
  32407. */
  32408. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32409. var vertexBuffer = this.getVertexBuffer(kind);
  32410. if (!vertexBuffer) {
  32411. return null;
  32412. }
  32413. var orig = vertexBuffer.getData();
  32414. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32415. return orig;
  32416. }
  32417. else {
  32418. var len = orig.length;
  32419. var copy = [];
  32420. for (var i = 0; i < len; i++) {
  32421. copy.push(orig[i]);
  32422. }
  32423. return copy;
  32424. }
  32425. };
  32426. /**
  32427. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32428. * @param kind defines the data kind (Position, normal, etc...)
  32429. * @returns true if the vertex buffer with the specified kind is updatable
  32430. */
  32431. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32432. var vb = this._vertexBuffers[kind];
  32433. if (!vb) {
  32434. return false;
  32435. }
  32436. return vb.isUpdatable();
  32437. };
  32438. /**
  32439. * Gets a specific vertex buffer
  32440. * @param kind defines the data kind (Position, normal, etc...)
  32441. * @returns a {BABYLON.VertexBuffer}
  32442. */
  32443. Geometry.prototype.getVertexBuffer = function (kind) {
  32444. if (!this.isReady()) {
  32445. return null;
  32446. }
  32447. return this._vertexBuffers[kind];
  32448. };
  32449. /**
  32450. * Returns all vertex buffers
  32451. * @return an object holding all vertex buffers indexed by kind
  32452. */
  32453. Geometry.prototype.getVertexBuffers = function () {
  32454. if (!this.isReady()) {
  32455. return null;
  32456. }
  32457. return this._vertexBuffers;
  32458. };
  32459. /**
  32460. * Gets a boolean indicating if specific vertex buffer is present
  32461. * @param kind defines the data kind (Position, normal, etc...)
  32462. * @returns true if data is present
  32463. */
  32464. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32465. if (!this._vertexBuffers) {
  32466. if (this._delayInfo) {
  32467. return this._delayInfo.indexOf(kind) !== -1;
  32468. }
  32469. return false;
  32470. }
  32471. return this._vertexBuffers[kind] !== undefined;
  32472. };
  32473. /**
  32474. * Gets a list of all attached data kinds (Position, normal, etc...)
  32475. * @returns a list of string containing all kinds
  32476. */
  32477. Geometry.prototype.getVerticesDataKinds = function () {
  32478. var result = [];
  32479. var kind;
  32480. if (!this._vertexBuffers && this._delayInfo) {
  32481. for (kind in this._delayInfo) {
  32482. result.push(kind);
  32483. }
  32484. }
  32485. else {
  32486. for (kind in this._vertexBuffers) {
  32487. result.push(kind);
  32488. }
  32489. }
  32490. return result;
  32491. };
  32492. /**
  32493. * Update index buffer
  32494. * @param indices defines the indices to store in the index buffer
  32495. * @param offset defines the offset in the target buffer where to store the data
  32496. */
  32497. Geometry.prototype.updateIndices = function (indices, offset) {
  32498. if (!this._indexBuffer) {
  32499. return;
  32500. }
  32501. if (!this._indexBufferIsUpdatable) {
  32502. this.setIndices(indices, null, true);
  32503. }
  32504. else {
  32505. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32506. }
  32507. };
  32508. /**
  32509. * Creates a new index buffer
  32510. * @param indices defines the indices to store in the index buffer
  32511. * @param totalVertices defines the total number of vertices (could be null)
  32512. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32513. */
  32514. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32515. if (totalVertices === void 0) { totalVertices = null; }
  32516. if (updatable === void 0) { updatable = false; }
  32517. if (this._indexBuffer) {
  32518. this._engine._releaseBuffer(this._indexBuffer);
  32519. }
  32520. this._disposeVertexArrayObjects();
  32521. this._indices = indices;
  32522. this._indexBufferIsUpdatable = updatable;
  32523. if (this._meshes.length !== 0 && this._indices) {
  32524. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32525. }
  32526. if (totalVertices != undefined) {
  32527. this._totalVertices = totalVertices;
  32528. }
  32529. var meshes = this._meshes;
  32530. var numOfMeshes = meshes.length;
  32531. for (var index = 0; index < numOfMeshes; index++) {
  32532. meshes[index]._createGlobalSubMesh(true);
  32533. }
  32534. this.notifyUpdate();
  32535. };
  32536. /**
  32537. * Return the total number of indices
  32538. * @returns the total number of indices
  32539. */
  32540. Geometry.prototype.getTotalIndices = function () {
  32541. if (!this.isReady()) {
  32542. return 0;
  32543. }
  32544. return this._indices.length;
  32545. };
  32546. /**
  32547. * Gets the index buffer array
  32548. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32549. * @returns the index buffer array
  32550. */
  32551. Geometry.prototype.getIndices = function (copyWhenShared) {
  32552. if (!this.isReady()) {
  32553. return null;
  32554. }
  32555. var orig = this._indices;
  32556. if (!copyWhenShared || this._meshes.length === 1) {
  32557. return orig;
  32558. }
  32559. else {
  32560. var len = orig.length;
  32561. var copy = [];
  32562. for (var i = 0; i < len; i++) {
  32563. copy.push(orig[i]);
  32564. }
  32565. return copy;
  32566. }
  32567. };
  32568. /**
  32569. * Gets the index buffer
  32570. * @return the index buffer
  32571. */
  32572. Geometry.prototype.getIndexBuffer = function () {
  32573. if (!this.isReady()) {
  32574. return null;
  32575. }
  32576. return this._indexBuffer;
  32577. };
  32578. /** @ignore */
  32579. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32580. if (effect === void 0) { effect = null; }
  32581. if (!effect || !this._vertexArrayObjects) {
  32582. return;
  32583. }
  32584. if (this._vertexArrayObjects[effect.key]) {
  32585. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32586. delete this._vertexArrayObjects[effect.key];
  32587. }
  32588. };
  32589. /**
  32590. * Release the associated resources for a specific mesh
  32591. * @param mesh defines the source mesh
  32592. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32593. */
  32594. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32595. var meshes = this._meshes;
  32596. var index = meshes.indexOf(mesh);
  32597. if (index === -1) {
  32598. return;
  32599. }
  32600. meshes.splice(index, 1);
  32601. mesh._geometry = null;
  32602. if (meshes.length === 0 && shouldDispose) {
  32603. this.dispose();
  32604. }
  32605. };
  32606. /**
  32607. * Apply current geometry to a given mesh
  32608. * @param mesh defines the mesh to apply geometry to
  32609. */
  32610. Geometry.prototype.applyToMesh = function (mesh) {
  32611. if (mesh._geometry === this) {
  32612. return;
  32613. }
  32614. var previousGeometry = mesh._geometry;
  32615. if (previousGeometry) {
  32616. previousGeometry.releaseForMesh(mesh);
  32617. }
  32618. var meshes = this._meshes;
  32619. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32620. mesh._geometry = this;
  32621. this._scene.pushGeometry(this);
  32622. meshes.push(mesh);
  32623. if (this.isReady()) {
  32624. this._applyToMesh(mesh);
  32625. }
  32626. else {
  32627. mesh._boundingInfo = this._boundingInfo;
  32628. }
  32629. };
  32630. Geometry.prototype.updateExtend = function (data, stride) {
  32631. if (data === void 0) { data = null; }
  32632. if (!data) {
  32633. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32634. }
  32635. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32636. };
  32637. Geometry.prototype._applyToMesh = function (mesh) {
  32638. var numOfMeshes = this._meshes.length;
  32639. // vertexBuffers
  32640. for (var kind in this._vertexBuffers) {
  32641. if (numOfMeshes === 1) {
  32642. this._vertexBuffers[kind].create();
  32643. }
  32644. var buffer = this._vertexBuffers[kind].getBuffer();
  32645. if (buffer)
  32646. buffer.references = numOfMeshes;
  32647. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32648. if (!this._extend) {
  32649. this.updateExtend(this._vertexBuffers[kind].getData());
  32650. }
  32651. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32652. mesh._createGlobalSubMesh(false);
  32653. //bounding info was just created again, world matrix should be applied again.
  32654. mesh._updateBoundingInfo();
  32655. }
  32656. }
  32657. // indexBuffer
  32658. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32659. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32660. }
  32661. if (this._indexBuffer) {
  32662. this._indexBuffer.references = numOfMeshes;
  32663. }
  32664. };
  32665. Geometry.prototype.notifyUpdate = function (kind) {
  32666. if (this.onGeometryUpdated) {
  32667. this.onGeometryUpdated(this, kind);
  32668. }
  32669. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32670. var mesh = _a[_i];
  32671. mesh._markSubMeshesAsAttributesDirty();
  32672. }
  32673. };
  32674. /**
  32675. * Load the geometry if it was flagged as delay loaded
  32676. * @param scene defines the hosting scene
  32677. * @param onLoaded defines a callback called when the geometry is loaded
  32678. */
  32679. Geometry.prototype.load = function (scene, onLoaded) {
  32680. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32681. return;
  32682. }
  32683. if (this.isReady()) {
  32684. if (onLoaded) {
  32685. onLoaded();
  32686. }
  32687. return;
  32688. }
  32689. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32690. this._queueLoad(scene, onLoaded);
  32691. };
  32692. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32693. var _this = this;
  32694. if (!this.delayLoadingFile) {
  32695. return;
  32696. }
  32697. scene._addPendingData(this);
  32698. scene._loadFile(this.delayLoadingFile, function (data) {
  32699. if (!_this._delayLoadingFunction) {
  32700. return;
  32701. }
  32702. _this._delayLoadingFunction(JSON.parse(data), _this);
  32703. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32704. _this._delayInfo = [];
  32705. scene._removePendingData(_this);
  32706. var meshes = _this._meshes;
  32707. var numOfMeshes = meshes.length;
  32708. for (var index = 0; index < numOfMeshes; index++) {
  32709. _this._applyToMesh(meshes[index]);
  32710. }
  32711. if (onLoaded) {
  32712. onLoaded();
  32713. }
  32714. }, undefined, true);
  32715. };
  32716. /**
  32717. * Invert the geometry to move from a right handed system to a left handed one.
  32718. */
  32719. Geometry.prototype.toLeftHanded = function () {
  32720. // Flip faces
  32721. var tIndices = this.getIndices(false);
  32722. if (tIndices != null && tIndices.length > 0) {
  32723. for (var i = 0; i < tIndices.length; i += 3) {
  32724. var tTemp = tIndices[i + 0];
  32725. tIndices[i + 0] = tIndices[i + 2];
  32726. tIndices[i + 2] = tTemp;
  32727. }
  32728. this.setIndices(tIndices);
  32729. }
  32730. // Negate position.z
  32731. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32732. if (tPositions != null && tPositions.length > 0) {
  32733. for (var i = 0; i < tPositions.length; i += 3) {
  32734. tPositions[i + 2] = -tPositions[i + 2];
  32735. }
  32736. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32737. }
  32738. // Negate normal.z
  32739. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32740. if (tNormals != null && tNormals.length > 0) {
  32741. for (var i = 0; i < tNormals.length; i += 3) {
  32742. tNormals[i + 2] = -tNormals[i + 2];
  32743. }
  32744. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32745. }
  32746. };
  32747. // Cache
  32748. /** @ignore */
  32749. Geometry.prototype._resetPointsArrayCache = function () {
  32750. this._positions = null;
  32751. };
  32752. /** @ignore */
  32753. Geometry.prototype._generatePointsArray = function () {
  32754. if (this._positions)
  32755. return true;
  32756. this._positions = [];
  32757. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32758. if (!data) {
  32759. return false;
  32760. }
  32761. for (var index = 0; index < data.length; index += 3) {
  32762. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32763. }
  32764. return true;
  32765. };
  32766. /**
  32767. * Gets a value indicating if the geometry is disposed
  32768. * @returns true if the geometry was disposed
  32769. */
  32770. Geometry.prototype.isDisposed = function () {
  32771. return this._isDisposed;
  32772. };
  32773. Geometry.prototype._disposeVertexArrayObjects = function () {
  32774. if (this._vertexArrayObjects) {
  32775. for (var kind in this._vertexArrayObjects) {
  32776. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32777. }
  32778. this._vertexArrayObjects = {};
  32779. }
  32780. };
  32781. /**
  32782. * Free all associated resources
  32783. */
  32784. Geometry.prototype.dispose = function () {
  32785. var meshes = this._meshes;
  32786. var numOfMeshes = meshes.length;
  32787. var index;
  32788. for (index = 0; index < numOfMeshes; index++) {
  32789. this.releaseForMesh(meshes[index]);
  32790. }
  32791. this._meshes = [];
  32792. this._disposeVertexArrayObjects();
  32793. for (var kind in this._vertexBuffers) {
  32794. this._vertexBuffers[kind].dispose();
  32795. }
  32796. this._vertexBuffers = {};
  32797. this._totalVertices = 0;
  32798. if (this._indexBuffer) {
  32799. this._engine._releaseBuffer(this._indexBuffer);
  32800. }
  32801. this._indexBuffer = null;
  32802. this._indices = [];
  32803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32804. this.delayLoadingFile = null;
  32805. this._delayLoadingFunction = null;
  32806. this._delayInfo = [];
  32807. this._boundingInfo = null;
  32808. this._scene.removeGeometry(this);
  32809. this._isDisposed = true;
  32810. };
  32811. /**
  32812. * Clone the current geometry into a new geometry
  32813. * @param id defines the unique ID of the new geometry
  32814. * @returns a new geometry object
  32815. */
  32816. Geometry.prototype.copy = function (id) {
  32817. var vertexData = new BABYLON.VertexData();
  32818. vertexData.indices = [];
  32819. var indices = this.getIndices();
  32820. if (indices) {
  32821. for (var index = 0; index < indices.length; index++) {
  32822. vertexData.indices.push(indices[index]);
  32823. }
  32824. }
  32825. var updatable = false;
  32826. var stopChecking = false;
  32827. var kind;
  32828. for (kind in this._vertexBuffers) {
  32829. // using slice() to make a copy of the array and not just reference it
  32830. var data = this.getVerticesData(kind);
  32831. if (data instanceof Float32Array) {
  32832. vertexData.set(new Float32Array(data), kind);
  32833. }
  32834. else {
  32835. vertexData.set(data.slice(0), kind);
  32836. }
  32837. if (!stopChecking) {
  32838. var vb = this.getVertexBuffer(kind);
  32839. if (vb) {
  32840. updatable = vb.isUpdatable();
  32841. stopChecking = !updatable;
  32842. }
  32843. }
  32844. }
  32845. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32846. geometry.delayLoadState = this.delayLoadState;
  32847. geometry.delayLoadingFile = this.delayLoadingFile;
  32848. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32849. for (kind in this._delayInfo) {
  32850. geometry._delayInfo = geometry._delayInfo || [];
  32851. geometry._delayInfo.push(kind);
  32852. }
  32853. // Bounding info
  32854. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32855. return geometry;
  32856. };
  32857. /**
  32858. * Serialize the current geometry info (and not the vertices data) into a JSON object
  32859. * @return a JSON representation of the current geometry data (without the vertices data)
  32860. */
  32861. Geometry.prototype.serialize = function () {
  32862. var serializationObject = {};
  32863. serializationObject.id = this.id;
  32864. serializationObject.updatable = this._updatable;
  32865. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32866. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32867. }
  32868. return serializationObject;
  32869. };
  32870. Geometry.prototype.toNumberArray = function (origin) {
  32871. if (Array.isArray(origin)) {
  32872. return origin;
  32873. }
  32874. else {
  32875. return Array.prototype.slice.call(origin);
  32876. }
  32877. };
  32878. /**
  32879. * Serialize all vertices data into a JSON oject
  32880. * @returns a JSON representation of the current geometry data
  32881. */
  32882. Geometry.prototype.serializeVerticeData = function () {
  32883. var serializationObject = this.serialize();
  32884. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32885. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32886. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32887. serializationObject.positions._updatable = true;
  32888. }
  32889. }
  32890. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32891. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32892. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32893. serializationObject.normals._updatable = true;
  32894. }
  32895. }
  32896. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32897. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  32898. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  32899. serializationObject.tangets._updatable = true;
  32900. }
  32901. }
  32902. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32903. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32904. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32905. serializationObject.uvs._updatable = true;
  32906. }
  32907. }
  32908. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32909. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32910. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32911. serializationObject.uv2s._updatable = true;
  32912. }
  32913. }
  32914. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32915. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32916. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32917. serializationObject.uv3s._updatable = true;
  32918. }
  32919. }
  32920. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32921. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32922. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32923. serializationObject.uv4s._updatable = true;
  32924. }
  32925. }
  32926. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32927. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32928. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32929. serializationObject.uv5s._updatable = true;
  32930. }
  32931. }
  32932. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32933. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32934. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32935. serializationObject.uv6s._updatable = true;
  32936. }
  32937. }
  32938. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32939. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32940. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32941. serializationObject.colors._updatable = true;
  32942. }
  32943. }
  32944. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32945. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32946. serializationObject.matricesIndices._isExpanded = true;
  32947. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32948. serializationObject.matricesIndices._updatable = true;
  32949. }
  32950. }
  32951. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32952. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32953. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32954. serializationObject.matricesWeights._updatable = true;
  32955. }
  32956. }
  32957. serializationObject.indices = this.toNumberArray(this.getIndices());
  32958. return serializationObject;
  32959. };
  32960. // Statics
  32961. /**
  32962. * Extracts a clone of a mesh geometry
  32963. * @param mesh defines the source mesh
  32964. * @param id defines the unique ID of the new geometry object
  32965. * @returns the new geometry object
  32966. */
  32967. Geometry.ExtractFromMesh = function (mesh, id) {
  32968. var geometry = mesh._geometry;
  32969. if (!geometry) {
  32970. return null;
  32971. }
  32972. return geometry.copy(id);
  32973. };
  32974. /**
  32975. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32976. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32977. * Be aware Math.random() could cause collisions, but:
  32978. * "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"
  32979. * @returns a string containing a new GUID
  32980. */
  32981. Geometry.RandomId = function () {
  32982. return BABYLON.Tools.RandomId();
  32983. };
  32984. /** @ignore */
  32985. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  32986. var scene = mesh.getScene();
  32987. // Geometry
  32988. var geometryId = parsedGeometry.geometryId;
  32989. if (geometryId) {
  32990. var geometry = scene.getGeometryByID(geometryId);
  32991. if (geometry) {
  32992. geometry.applyToMesh(mesh);
  32993. }
  32994. }
  32995. else if (parsedGeometry instanceof ArrayBuffer) {
  32996. var binaryInfo = mesh._binaryInfo;
  32997. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32998. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32999. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33000. }
  33001. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33002. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33003. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33004. }
  33005. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33006. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33007. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33008. }
  33009. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33010. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33011. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33012. }
  33013. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33014. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33015. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33016. }
  33017. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33018. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33019. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33020. }
  33021. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33022. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33023. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33024. }
  33025. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33026. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33027. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33028. }
  33029. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33030. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33031. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33032. }
  33033. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33034. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33035. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33036. }
  33037. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33038. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33039. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33040. }
  33041. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33042. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33043. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33044. }
  33045. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33046. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33047. mesh.setIndices(indicesData, null);
  33048. }
  33049. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33050. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33051. mesh.subMeshes = [];
  33052. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33053. var materialIndex = subMeshesData[(i * 5) + 0];
  33054. var verticesStart = subMeshesData[(i * 5) + 1];
  33055. var verticesCount = subMeshesData[(i * 5) + 2];
  33056. var indexStart = subMeshesData[(i * 5) + 3];
  33057. var indexCount = subMeshesData[(i * 5) + 4];
  33058. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33059. }
  33060. }
  33061. }
  33062. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33063. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33064. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33065. if (parsedGeometry.tangents) {
  33066. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33067. }
  33068. if (parsedGeometry.uvs) {
  33069. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33070. }
  33071. if (parsedGeometry.uvs2) {
  33072. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33073. }
  33074. if (parsedGeometry.uvs3) {
  33075. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33076. }
  33077. if (parsedGeometry.uvs4) {
  33078. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33079. }
  33080. if (parsedGeometry.uvs5) {
  33081. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33082. }
  33083. if (parsedGeometry.uvs6) {
  33084. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33085. }
  33086. if (parsedGeometry.colors) {
  33087. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33088. }
  33089. if (parsedGeometry.matricesIndices) {
  33090. if (!parsedGeometry.matricesIndices._isExpanded) {
  33091. var floatIndices = [];
  33092. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33093. var matricesIndex = parsedGeometry.matricesIndices[i];
  33094. floatIndices.push(matricesIndex & 0x000000FF);
  33095. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33096. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33097. floatIndices.push(matricesIndex >> 24);
  33098. }
  33099. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33100. }
  33101. else {
  33102. delete parsedGeometry.matricesIndices._isExpanded;
  33103. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33104. }
  33105. }
  33106. if (parsedGeometry.matricesIndicesExtra) {
  33107. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33108. var floatIndices = [];
  33109. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33110. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33111. floatIndices.push(matricesIndex & 0x000000FF);
  33112. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33113. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33114. floatIndices.push(matricesIndex >> 24);
  33115. }
  33116. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33117. }
  33118. else {
  33119. delete parsedGeometry.matricesIndices._isExpanded;
  33120. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33121. }
  33122. }
  33123. if (parsedGeometry.matricesWeights) {
  33124. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33125. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33126. }
  33127. if (parsedGeometry.matricesWeightsExtra) {
  33128. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33129. }
  33130. mesh.setIndices(parsedGeometry.indices, null);
  33131. }
  33132. // SubMeshes
  33133. if (parsedGeometry.subMeshes) {
  33134. mesh.subMeshes = [];
  33135. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33136. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33137. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33138. }
  33139. }
  33140. // Flat shading
  33141. if (mesh._shouldGenerateFlatShading) {
  33142. mesh.convertToFlatShadedMesh();
  33143. delete mesh._shouldGenerateFlatShading;
  33144. }
  33145. // Update
  33146. mesh.computeWorldMatrix(true);
  33147. // Octree
  33148. var sceneOctree = scene.selectionOctree;
  33149. if (sceneOctree !== undefined && sceneOctree !== null) {
  33150. sceneOctree.addMesh(mesh);
  33151. }
  33152. };
  33153. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33154. var epsilon = 1e-3;
  33155. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33156. return;
  33157. }
  33158. var noInfluenceBoneIndex = 0.0;
  33159. if (parsedGeometry.skeletonId > -1) {
  33160. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33161. if (!skeleton) {
  33162. return;
  33163. }
  33164. noInfluenceBoneIndex = skeleton.bones.length;
  33165. }
  33166. else {
  33167. return;
  33168. }
  33169. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33170. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33171. var matricesWeights = parsedGeometry.matricesWeights;
  33172. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33173. var influencers = parsedGeometry.numBoneInfluencer;
  33174. var size = matricesWeights.length;
  33175. for (var i = 0; i < size; i += 4) {
  33176. var weight = 0.0;
  33177. var firstZeroWeight = -1;
  33178. for (var j = 0; j < 4; j++) {
  33179. var w = matricesWeights[i + j];
  33180. weight += w;
  33181. if (w < epsilon && firstZeroWeight < 0) {
  33182. firstZeroWeight = j;
  33183. }
  33184. }
  33185. if (matricesWeightsExtra) {
  33186. for (var j = 0; j < 4; j++) {
  33187. var w = matricesWeightsExtra[i + j];
  33188. weight += w;
  33189. if (w < epsilon && firstZeroWeight < 0) {
  33190. firstZeroWeight = j + 4;
  33191. }
  33192. }
  33193. }
  33194. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33195. firstZeroWeight = influencers - 1;
  33196. }
  33197. if (weight > epsilon) {
  33198. var mweight = 1.0 / weight;
  33199. for (var j = 0; j < 4; j++) {
  33200. matricesWeights[i + j] *= mweight;
  33201. }
  33202. if (matricesWeightsExtra) {
  33203. for (var j = 0; j < 4; j++) {
  33204. matricesWeightsExtra[i + j] *= mweight;
  33205. }
  33206. }
  33207. }
  33208. else {
  33209. if (firstZeroWeight >= 4) {
  33210. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33211. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33212. }
  33213. else {
  33214. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33215. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33216. }
  33217. }
  33218. }
  33219. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33220. if (parsedGeometry.matricesWeightsExtra) {
  33221. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33222. }
  33223. };
  33224. /**
  33225. * Create a new geometry from persisted data (Using .babylon file format)
  33226. * @param parsedVertexData defines the persisted data
  33227. * @param scene defines the hosting scene
  33228. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33229. * @returns the new geometry object
  33230. */
  33231. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33232. if (scene.getGeometryByID(parsedVertexData.id)) {
  33233. return null; // null since geometry could be something else than a box...
  33234. }
  33235. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33236. if (BABYLON.Tags) {
  33237. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33238. }
  33239. if (parsedVertexData.delayLoadingFile) {
  33240. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33241. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33242. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33243. geometry._delayInfo = [];
  33244. if (parsedVertexData.hasUVs) {
  33245. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33246. }
  33247. if (parsedVertexData.hasUVs2) {
  33248. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33249. }
  33250. if (parsedVertexData.hasUVs3) {
  33251. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33252. }
  33253. if (parsedVertexData.hasUVs4) {
  33254. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33255. }
  33256. if (parsedVertexData.hasUVs5) {
  33257. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33258. }
  33259. if (parsedVertexData.hasUVs6) {
  33260. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33261. }
  33262. if (parsedVertexData.hasColors) {
  33263. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33264. }
  33265. if (parsedVertexData.hasMatricesIndices) {
  33266. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33267. }
  33268. if (parsedVertexData.hasMatricesWeights) {
  33269. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33270. }
  33271. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33272. }
  33273. else {
  33274. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33275. }
  33276. scene.pushGeometry(geometry, true);
  33277. return geometry;
  33278. };
  33279. return Geometry;
  33280. }());
  33281. BABYLON.Geometry = Geometry;
  33282. // Primitives
  33283. /// Abstract class
  33284. /**
  33285. * Abstract class used to provide common services for all typed geometries
  33286. */
  33287. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33288. __extends(_PrimitiveGeometry, _super);
  33289. /**
  33290. * Creates a new typed geometry
  33291. * @param id defines the unique ID of the geometry
  33292. * @param scene defines the hosting scene
  33293. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33294. * @param mesh defines the hosting mesh (can be null)
  33295. */
  33296. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33297. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33298. if (mesh === void 0) { mesh = null; }
  33299. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33300. _this._canBeRegenerated = _canBeRegenerated;
  33301. _this._beingRegenerated = true;
  33302. _this.regenerate();
  33303. _this._beingRegenerated = false;
  33304. return _this;
  33305. }
  33306. /**
  33307. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33308. * @returns true if the geometry can be regenerated
  33309. */
  33310. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33311. return this._canBeRegenerated;
  33312. };
  33313. /**
  33314. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33315. */
  33316. _PrimitiveGeometry.prototype.regenerate = function () {
  33317. if (!this._canBeRegenerated) {
  33318. return;
  33319. }
  33320. this._beingRegenerated = true;
  33321. this.setAllVerticesData(this._regenerateVertexData(), false);
  33322. this._beingRegenerated = false;
  33323. };
  33324. /**
  33325. * Clone the geometry
  33326. * @param id defines the unique ID of the new geometry
  33327. * @returns the new geometry
  33328. */
  33329. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33330. return _super.prototype.copy.call(this, id);
  33331. };
  33332. // overrides
  33333. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33334. if (!this._beingRegenerated) {
  33335. return;
  33336. }
  33337. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33338. };
  33339. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33340. if (!this._beingRegenerated) {
  33341. return;
  33342. }
  33343. _super.prototype.setVerticesData.call(this, kind, data, false);
  33344. };
  33345. // to override
  33346. /** @ignore */
  33347. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33348. throw new Error("Abstract method");
  33349. };
  33350. _PrimitiveGeometry.prototype.copy = function (id) {
  33351. throw new Error("Must be overriden in sub-classes.");
  33352. };
  33353. _PrimitiveGeometry.prototype.serialize = function () {
  33354. var serializationObject = _super.prototype.serialize.call(this);
  33355. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33356. return serializationObject;
  33357. };
  33358. return _PrimitiveGeometry;
  33359. }(Geometry));
  33360. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33361. /**
  33362. * Creates a ribbon geometry
  33363. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33364. */
  33365. var RibbonGeometry = /** @class */ (function (_super) {
  33366. __extends(RibbonGeometry, _super);
  33367. /**
  33368. * Creates a ribbon geometry
  33369. * @param id defines the unique ID of the geometry
  33370. * @param scene defines the hosting scene
  33371. * @param pathArray defines the array of paths to use
  33372. * @param closeArray defines if the last path and the first path must be joined
  33373. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33374. * @param offset defines the offset between points
  33375. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33376. * @param mesh defines the hosting mesh (can be null)
  33377. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33378. */
  33379. function RibbonGeometry(id, scene,
  33380. /**
  33381. * Defines the array of paths to use
  33382. */
  33383. pathArray,
  33384. /**
  33385. * Defines if the last and first points of each path in your pathArray must be joined
  33386. */
  33387. closeArray,
  33388. /**
  33389. * Defines if the last and first points of each path in your pathArray must be joined
  33390. */
  33391. closePath,
  33392. /**
  33393. * Defines the offset between points
  33394. */
  33395. offset, canBeRegenerated, mesh,
  33396. /**
  33397. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33398. */
  33399. side) {
  33400. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33401. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33402. _this.pathArray = pathArray;
  33403. _this.closeArray = closeArray;
  33404. _this.closePath = closePath;
  33405. _this.offset = offset;
  33406. _this.side = side;
  33407. return _this;
  33408. }
  33409. /** @ignore */
  33410. RibbonGeometry.prototype._regenerateVertexData = function () {
  33411. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33412. };
  33413. RibbonGeometry.prototype.copy = function (id) {
  33414. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33415. };
  33416. return RibbonGeometry;
  33417. }(_PrimitiveGeometry));
  33418. BABYLON.RibbonGeometry = RibbonGeometry;
  33419. /**
  33420. * Creates a box geometry
  33421. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33422. */
  33423. var BoxGeometry = /** @class */ (function (_super) {
  33424. __extends(BoxGeometry, _super);
  33425. /**
  33426. * Creates a box geometry
  33427. * @param id defines the unique ID of the geometry
  33428. * @param scene defines the hosting scene
  33429. * @param size defines the zise of the box (width, height and depth are the same)
  33430. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33431. * @param mesh defines the hosting mesh (can be null)
  33432. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33433. */
  33434. function BoxGeometry(id, scene,
  33435. /**
  33436. * Defines the zise of the box (width, height and depth are the same)
  33437. */
  33438. size, canBeRegenerated, mesh,
  33439. /**
  33440. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33441. */
  33442. side) {
  33443. if (mesh === void 0) { mesh = null; }
  33444. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33445. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33446. _this.size = size;
  33447. _this.side = side;
  33448. return _this;
  33449. }
  33450. BoxGeometry.prototype._regenerateVertexData = function () {
  33451. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33452. };
  33453. BoxGeometry.prototype.copy = function (id) {
  33454. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33455. };
  33456. BoxGeometry.prototype.serialize = function () {
  33457. var serializationObject = _super.prototype.serialize.call(this);
  33458. serializationObject.size = this.size;
  33459. return serializationObject;
  33460. };
  33461. BoxGeometry.Parse = function (parsedBox, scene) {
  33462. if (scene.getGeometryByID(parsedBox.id)) {
  33463. return null; // null since geometry could be something else than a box...
  33464. }
  33465. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33466. if (BABYLON.Tags) {
  33467. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33468. }
  33469. scene.pushGeometry(box, true);
  33470. return box;
  33471. };
  33472. return BoxGeometry;
  33473. }(_PrimitiveGeometry));
  33474. BABYLON.BoxGeometry = BoxGeometry;
  33475. /**
  33476. * Creates a sphere geometry
  33477. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33478. */
  33479. var SphereGeometry = /** @class */ (function (_super) {
  33480. __extends(SphereGeometry, _super);
  33481. /**
  33482. * Create a new sphere geometry
  33483. * @param id defines the unique ID of the geometry
  33484. * @param scene defines the hosting scene
  33485. * @param segments defines the number of segments to use to create the sphere
  33486. * @param diameter defines the diameter of the sphere
  33487. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33488. * @param mesh defines the hosting mesh (can be null)
  33489. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33490. */
  33491. function SphereGeometry(id, scene,
  33492. /**
  33493. * Defines the number of segments to use to create the sphere
  33494. */
  33495. segments,
  33496. /**
  33497. * Defines the diameter of the sphere
  33498. */
  33499. diameter, canBeRegenerated, mesh,
  33500. /**
  33501. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33502. */
  33503. side) {
  33504. if (mesh === void 0) { mesh = null; }
  33505. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33506. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33507. _this.segments = segments;
  33508. _this.diameter = diameter;
  33509. _this.side = side;
  33510. return _this;
  33511. }
  33512. SphereGeometry.prototype._regenerateVertexData = function () {
  33513. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33514. };
  33515. SphereGeometry.prototype.copy = function (id) {
  33516. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33517. };
  33518. SphereGeometry.prototype.serialize = function () {
  33519. var serializationObject = _super.prototype.serialize.call(this);
  33520. serializationObject.segments = this.segments;
  33521. serializationObject.diameter = this.diameter;
  33522. return serializationObject;
  33523. };
  33524. SphereGeometry.Parse = function (parsedSphere, scene) {
  33525. if (scene.getGeometryByID(parsedSphere.id)) {
  33526. return null; // null since geometry could be something else than a sphere...
  33527. }
  33528. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33529. if (BABYLON.Tags) {
  33530. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33531. }
  33532. scene.pushGeometry(sphere, true);
  33533. return sphere;
  33534. };
  33535. return SphereGeometry;
  33536. }(_PrimitiveGeometry));
  33537. BABYLON.SphereGeometry = SphereGeometry;
  33538. /**
  33539. * Creates a disc geometry
  33540. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33541. */
  33542. var DiscGeometry = /** @class */ (function (_super) {
  33543. __extends(DiscGeometry, _super);
  33544. /**
  33545. * Creates a new disc geometry
  33546. * @param id defines the unique ID of the geometry
  33547. * @param scene defines the hosting scene
  33548. * @param radius defines the radius of the disc
  33549. * @param tessellation defines the tesselation factor to apply to the disc
  33550. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33551. * @param mesh defines the hosting mesh (can be null)
  33552. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33553. */
  33554. function DiscGeometry(id, scene,
  33555. /**
  33556. * Defines the radius of the disc
  33557. */
  33558. radius,
  33559. /**
  33560. * Defines the tesselation factor to apply to the disc
  33561. */
  33562. tessellation, canBeRegenerated, mesh,
  33563. /**
  33564. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33565. */
  33566. side) {
  33567. if (mesh === void 0) { mesh = null; }
  33568. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33569. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33570. _this.radius = radius;
  33571. _this.tessellation = tessellation;
  33572. _this.side = side;
  33573. return _this;
  33574. }
  33575. DiscGeometry.prototype._regenerateVertexData = function () {
  33576. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33577. };
  33578. DiscGeometry.prototype.copy = function (id) {
  33579. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33580. };
  33581. return DiscGeometry;
  33582. }(_PrimitiveGeometry));
  33583. BABYLON.DiscGeometry = DiscGeometry;
  33584. /**
  33585. * Creates a new cylinder geometry
  33586. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33587. */
  33588. var CylinderGeometry = /** @class */ (function (_super) {
  33589. __extends(CylinderGeometry, _super);
  33590. /**
  33591. * Creates a new cylinder geometry
  33592. * @param id defines the unique ID of the geometry
  33593. * @param scene defines the hosting scene
  33594. * @param height defines the height of the cylinder
  33595. * @param diameterTop defines the diameter of the cylinder's top cap
  33596. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33597. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33598. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33599. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33600. * @param mesh defines the hosting mesh (can be null)
  33601. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33602. */
  33603. function CylinderGeometry(id, scene,
  33604. /**
  33605. * Defines the height of the cylinder
  33606. */
  33607. height,
  33608. /**
  33609. * Defines the diameter of the cylinder's top cap
  33610. */
  33611. diameterTop,
  33612. /**
  33613. * Defines the diameter of the cylinder's bottom cap
  33614. */
  33615. diameterBottom,
  33616. /**
  33617. * Defines the tessellation factor to apply to the cylinder
  33618. */
  33619. tessellation,
  33620. /**
  33621. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33622. */
  33623. subdivisions, canBeRegenerated, mesh,
  33624. /**
  33625. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33626. */
  33627. side) {
  33628. if (subdivisions === void 0) { subdivisions = 1; }
  33629. if (mesh === void 0) { mesh = null; }
  33630. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33631. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33632. _this.height = height;
  33633. _this.diameterTop = diameterTop;
  33634. _this.diameterBottom = diameterBottom;
  33635. _this.tessellation = tessellation;
  33636. _this.subdivisions = subdivisions;
  33637. _this.side = side;
  33638. return _this;
  33639. }
  33640. CylinderGeometry.prototype._regenerateVertexData = function () {
  33641. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33642. };
  33643. CylinderGeometry.prototype.copy = function (id) {
  33644. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33645. };
  33646. CylinderGeometry.prototype.serialize = function () {
  33647. var serializationObject = _super.prototype.serialize.call(this);
  33648. serializationObject.height = this.height;
  33649. serializationObject.diameterTop = this.diameterTop;
  33650. serializationObject.diameterBottom = this.diameterBottom;
  33651. serializationObject.tessellation = this.tessellation;
  33652. return serializationObject;
  33653. };
  33654. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  33655. if (scene.getGeometryByID(parsedCylinder.id)) {
  33656. return null; // null since geometry could be something else than a cylinder...
  33657. }
  33658. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33659. if (BABYLON.Tags) {
  33660. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33661. }
  33662. scene.pushGeometry(cylinder, true);
  33663. return cylinder;
  33664. };
  33665. return CylinderGeometry;
  33666. }(_PrimitiveGeometry));
  33667. BABYLON.CylinderGeometry = CylinderGeometry;
  33668. /**
  33669. * Creates a new torus geometry
  33670. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  33671. */
  33672. var TorusGeometry = /** @class */ (function (_super) {
  33673. __extends(TorusGeometry, _super);
  33674. /**
  33675. * Creates a new torus geometry
  33676. * @param id defines the unique ID of the geometry
  33677. * @param scene defines the hosting scene
  33678. * @param diameter defines the diameter of the torus
  33679. * @param thickness defines the thickness of the torus (ie. internal diameter)
  33680. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  33681. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33682. * @param mesh defines the hosting mesh (can be null)
  33683. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33684. */
  33685. function TorusGeometry(id, scene,
  33686. /**
  33687. * Defines the diameter of the torus
  33688. */
  33689. diameter,
  33690. /**
  33691. * Defines the thickness of the torus (ie. internal diameter)
  33692. */
  33693. thickness,
  33694. /**
  33695. * Defines the tesselation factor to apply to the torus
  33696. */
  33697. tessellation, canBeRegenerated, mesh,
  33698. /**
  33699. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33700. */
  33701. side) {
  33702. if (mesh === void 0) { mesh = null; }
  33703. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33704. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33705. _this.diameter = diameter;
  33706. _this.thickness = thickness;
  33707. _this.tessellation = tessellation;
  33708. _this.side = side;
  33709. return _this;
  33710. }
  33711. TorusGeometry.prototype._regenerateVertexData = function () {
  33712. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33713. };
  33714. TorusGeometry.prototype.copy = function (id) {
  33715. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33716. };
  33717. TorusGeometry.prototype.serialize = function () {
  33718. var serializationObject = _super.prototype.serialize.call(this);
  33719. serializationObject.diameter = this.diameter;
  33720. serializationObject.thickness = this.thickness;
  33721. serializationObject.tessellation = this.tessellation;
  33722. return serializationObject;
  33723. };
  33724. TorusGeometry.Parse = function (parsedTorus, scene) {
  33725. if (scene.getGeometryByID(parsedTorus.id)) {
  33726. return null; // null since geometry could be something else than a torus...
  33727. }
  33728. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33729. if (BABYLON.Tags) {
  33730. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33731. }
  33732. scene.pushGeometry(torus, true);
  33733. return torus;
  33734. };
  33735. return TorusGeometry;
  33736. }(_PrimitiveGeometry));
  33737. BABYLON.TorusGeometry = TorusGeometry;
  33738. /**
  33739. * Creates a new ground geometry
  33740. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  33741. */
  33742. var GroundGeometry = /** @class */ (function (_super) {
  33743. __extends(GroundGeometry, _super);
  33744. /**
  33745. * Creates a new ground geometry
  33746. * @param id defines the unique ID of the geometry
  33747. * @param scene defines the hosting scene
  33748. * @param width defines the width of the ground
  33749. * @param height defines the height of the ground
  33750. * @param subdivisions defines the subdivisions to apply to the ground
  33751. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33752. * @param mesh defines the hosting mesh (can be null)
  33753. */
  33754. function GroundGeometry(id, scene,
  33755. /**
  33756. * Defines the width of the ground
  33757. */
  33758. width,
  33759. /**
  33760. * Defines the height of the ground
  33761. */
  33762. height,
  33763. /**
  33764. * Defines the subdivisions to apply to the ground
  33765. */
  33766. subdivisions, canBeRegenerated, mesh) {
  33767. if (mesh === void 0) { mesh = null; }
  33768. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33769. _this.width = width;
  33770. _this.height = height;
  33771. _this.subdivisions = subdivisions;
  33772. return _this;
  33773. }
  33774. GroundGeometry.prototype._regenerateVertexData = function () {
  33775. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33776. };
  33777. GroundGeometry.prototype.copy = function (id) {
  33778. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33779. };
  33780. GroundGeometry.prototype.serialize = function () {
  33781. var serializationObject = _super.prototype.serialize.call(this);
  33782. serializationObject.width = this.width;
  33783. serializationObject.height = this.height;
  33784. serializationObject.subdivisions = this.subdivisions;
  33785. return serializationObject;
  33786. };
  33787. GroundGeometry.Parse = function (parsedGround, scene) {
  33788. if (scene.getGeometryByID(parsedGround.id)) {
  33789. return null; // null since geometry could be something else than a ground...
  33790. }
  33791. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33792. if (BABYLON.Tags) {
  33793. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33794. }
  33795. scene.pushGeometry(ground, true);
  33796. return ground;
  33797. };
  33798. return GroundGeometry;
  33799. }(_PrimitiveGeometry));
  33800. BABYLON.GroundGeometry = GroundGeometry;
  33801. /**
  33802. * Creates a tiled ground geometry
  33803. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  33804. */
  33805. var TiledGroundGeometry = /** @class */ (function (_super) {
  33806. __extends(TiledGroundGeometry, _super);
  33807. /**
  33808. * Creates a tiled ground geometry
  33809. * @param id defines the unique ID of the geometry
  33810. * @param scene defines the hosting scene
  33811. * @param xmin defines the minimum value on X axis
  33812. * @param zmin defines the minimum value on Z axis
  33813. * @param xmax defines the maximum value on X axis
  33814. * @param zmax defines the maximum value on Z axis
  33815. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  33816. * @param precision defines the precision to use when computing the tiles
  33817. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33818. * @param mesh defines the hosting mesh (can be null)
  33819. */
  33820. function TiledGroundGeometry(id, scene,
  33821. /**
  33822. * Defines the minimum value on X axis
  33823. */
  33824. xmin,
  33825. /**
  33826. * Defines the minimum value on Z axis
  33827. */
  33828. zmin,
  33829. /**
  33830. * Defines the maximum value on X axis
  33831. */
  33832. xmax,
  33833. /**
  33834. * Defines the maximum value on Z axis
  33835. */
  33836. zmax,
  33837. /**
  33838. * Defines the subdivisions to apply to the ground
  33839. */
  33840. subdivisions,
  33841. /**
  33842. * Defines the precision to use when computing the tiles
  33843. */
  33844. precision, canBeRegenerated, mesh) {
  33845. if (mesh === void 0) { mesh = null; }
  33846. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33847. _this.xmin = xmin;
  33848. _this.zmin = zmin;
  33849. _this.xmax = xmax;
  33850. _this.zmax = zmax;
  33851. _this.subdivisions = subdivisions;
  33852. _this.precision = precision;
  33853. return _this;
  33854. }
  33855. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  33856. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33857. };
  33858. TiledGroundGeometry.prototype.copy = function (id) {
  33859. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33860. };
  33861. return TiledGroundGeometry;
  33862. }(_PrimitiveGeometry));
  33863. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  33864. /**
  33865. * Creates a plane geometry
  33866. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  33867. */
  33868. var PlaneGeometry = /** @class */ (function (_super) {
  33869. __extends(PlaneGeometry, _super);
  33870. /**
  33871. * Creates a plane geometry
  33872. * @param id defines the unique ID of the geometry
  33873. * @param scene defines the hosting scene
  33874. * @param size defines the size of the plane (width === height)
  33875. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33876. * @param mesh defines the hosting mesh (can be null)
  33877. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33878. */
  33879. function PlaneGeometry(id, scene,
  33880. /**
  33881. * Defines the size of the plane (width === height)
  33882. */
  33883. size, canBeRegenerated, mesh,
  33884. /**
  33885. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33886. */
  33887. side) {
  33888. if (mesh === void 0) { mesh = null; }
  33889. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33890. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33891. _this.size = size;
  33892. _this.side = side;
  33893. return _this;
  33894. }
  33895. PlaneGeometry.prototype._regenerateVertexData = function () {
  33896. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33897. };
  33898. PlaneGeometry.prototype.copy = function (id) {
  33899. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33900. };
  33901. PlaneGeometry.prototype.serialize = function () {
  33902. var serializationObject = _super.prototype.serialize.call(this);
  33903. serializationObject.size = this.size;
  33904. return serializationObject;
  33905. };
  33906. PlaneGeometry.Parse = function (parsedPlane, scene) {
  33907. if (scene.getGeometryByID(parsedPlane.id)) {
  33908. return null; // null since geometry could be something else than a ground...
  33909. }
  33910. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33911. if (BABYLON.Tags) {
  33912. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33913. }
  33914. scene.pushGeometry(plane, true);
  33915. return plane;
  33916. };
  33917. return PlaneGeometry;
  33918. }(_PrimitiveGeometry));
  33919. BABYLON.PlaneGeometry = PlaneGeometry;
  33920. /**
  33921. * Creates a torus knot geometry
  33922. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  33923. */
  33924. var TorusKnotGeometry = /** @class */ (function (_super) {
  33925. __extends(TorusKnotGeometry, _super);
  33926. /**
  33927. * Creates a torus knot geometry
  33928. * @param id defines the unique ID of the geometry
  33929. * @param scene defines the hosting scene
  33930. * @param radius defines the radius of the torus knot
  33931. * @param tube defines the thickness of the torus knot tube
  33932. * @param radialSegments defines the number of radial segments
  33933. * @param tubularSegments defines the number of tubular segments
  33934. * @param p defines the first number of windings
  33935. * @param q defines the second number of windings
  33936. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33937. * @param mesh defines the hosting mesh (can be null)
  33938. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33939. */
  33940. function TorusKnotGeometry(id, scene,
  33941. /**
  33942. * Defines the radius of the torus knot
  33943. */
  33944. radius,
  33945. /**
  33946. * Defines the thickness of the torus knot tube
  33947. */
  33948. tube,
  33949. /**
  33950. * Defines the number of radial segments
  33951. */
  33952. radialSegments,
  33953. /**
  33954. * Defines the number of tubular segments
  33955. */
  33956. tubularSegments,
  33957. /**
  33958. * Defines the first number of windings
  33959. */
  33960. p,
  33961. /**
  33962. * Defines the second number of windings
  33963. */
  33964. q, canBeRegenerated, mesh,
  33965. /**
  33966. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33967. */
  33968. side) {
  33969. if (mesh === void 0) { mesh = null; }
  33970. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33971. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33972. _this.radius = radius;
  33973. _this.tube = tube;
  33974. _this.radialSegments = radialSegments;
  33975. _this.tubularSegments = tubularSegments;
  33976. _this.p = p;
  33977. _this.q = q;
  33978. _this.side = side;
  33979. return _this;
  33980. }
  33981. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  33982. 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 });
  33983. };
  33984. TorusKnotGeometry.prototype.copy = function (id) {
  33985. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33986. };
  33987. TorusKnotGeometry.prototype.serialize = function () {
  33988. var serializationObject = _super.prototype.serialize.call(this);
  33989. serializationObject.radius = this.radius;
  33990. serializationObject.tube = this.tube;
  33991. serializationObject.radialSegments = this.radialSegments;
  33992. serializationObject.tubularSegments = this.tubularSegments;
  33993. serializationObject.p = this.p;
  33994. serializationObject.q = this.q;
  33995. return serializationObject;
  33996. };
  33997. ;
  33998. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  33999. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34000. return null; // null since geometry could be something else than a ground...
  34001. }
  34002. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34003. if (BABYLON.Tags) {
  34004. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34005. }
  34006. scene.pushGeometry(torusKnot, true);
  34007. return torusKnot;
  34008. };
  34009. return TorusKnotGeometry;
  34010. }(_PrimitiveGeometry));
  34011. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34012. //}
  34013. })(BABYLON || (BABYLON = {}));
  34014. //# sourceMappingURL=babylon.geometry.js.map
  34015. var BABYLON;
  34016. (function (BABYLON) {
  34017. var PostProcessManager = /** @class */ (function () {
  34018. function PostProcessManager(scene) {
  34019. this._vertexBuffers = {};
  34020. this._scene = scene;
  34021. }
  34022. PostProcessManager.prototype._prepareBuffers = function () {
  34023. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34024. return;
  34025. }
  34026. // VBO
  34027. var vertices = [];
  34028. vertices.push(1, 1);
  34029. vertices.push(-1, 1);
  34030. vertices.push(-1, -1);
  34031. vertices.push(1, -1);
  34032. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34033. this._buildIndexBuffer();
  34034. };
  34035. PostProcessManager.prototype._buildIndexBuffer = function () {
  34036. // Indices
  34037. var indices = [];
  34038. indices.push(0);
  34039. indices.push(1);
  34040. indices.push(2);
  34041. indices.push(0);
  34042. indices.push(2);
  34043. indices.push(3);
  34044. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34045. };
  34046. PostProcessManager.prototype._rebuild = function () {
  34047. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34048. if (!vb) {
  34049. return;
  34050. }
  34051. vb._rebuild();
  34052. this._buildIndexBuffer();
  34053. };
  34054. // Methods
  34055. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34056. if (sourceTexture === void 0) { sourceTexture = null; }
  34057. if (postProcesses === void 0) { postProcesses = null; }
  34058. var camera = this._scene.activeCamera;
  34059. if (!camera) {
  34060. return false;
  34061. }
  34062. var postProcesses = postProcesses || camera._postProcesses;
  34063. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34064. return false;
  34065. }
  34066. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34067. return true;
  34068. };
  34069. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34070. if (targetTexture === void 0) { targetTexture = null; }
  34071. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34072. var engine = this._scene.getEngine();
  34073. for (var index = 0; index < postProcesses.length; index++) {
  34074. if (index < postProcesses.length - 1) {
  34075. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34076. }
  34077. else {
  34078. if (targetTexture) {
  34079. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34080. }
  34081. else {
  34082. engine.restoreDefaultFramebuffer();
  34083. }
  34084. }
  34085. var pp = postProcesses[index];
  34086. var effect = pp.apply();
  34087. if (effect) {
  34088. pp.onBeforeRenderObservable.notifyObservers(effect);
  34089. // VBOs
  34090. this._prepareBuffers();
  34091. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34092. // Draw order
  34093. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34094. pp.onAfterRenderObservable.notifyObservers(effect);
  34095. }
  34096. }
  34097. // Restore depth buffer
  34098. engine.setDepthBuffer(true);
  34099. engine.setDepthWrite(true);
  34100. };
  34101. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34102. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34103. var camera = this._scene.activeCamera;
  34104. if (!camera) {
  34105. return;
  34106. }
  34107. postProcesses = postProcesses || camera._postProcesses;
  34108. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34109. return;
  34110. }
  34111. var engine = this._scene.getEngine();
  34112. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34113. if (index < len - 1) {
  34114. postProcesses[index + 1].activate(camera, targetTexture);
  34115. }
  34116. else {
  34117. if (targetTexture) {
  34118. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34119. }
  34120. else {
  34121. engine.restoreDefaultFramebuffer();
  34122. }
  34123. }
  34124. if (doNotPresent) {
  34125. break;
  34126. }
  34127. var pp = postProcesses[index];
  34128. var effect = pp.apply();
  34129. if (effect) {
  34130. pp.onBeforeRenderObservable.notifyObservers(effect);
  34131. // VBOs
  34132. this._prepareBuffers();
  34133. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34134. // Draw order
  34135. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34136. pp.onAfterRenderObservable.notifyObservers(effect);
  34137. }
  34138. }
  34139. // Restore states
  34140. engine.setDepthBuffer(true);
  34141. engine.setDepthWrite(true);
  34142. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34143. };
  34144. PostProcessManager.prototype.dispose = function () {
  34145. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34146. if (buffer) {
  34147. buffer.dispose();
  34148. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34149. }
  34150. if (this._indexBuffer) {
  34151. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34152. this._indexBuffer = null;
  34153. }
  34154. };
  34155. return PostProcessManager;
  34156. }());
  34157. BABYLON.PostProcessManager = PostProcessManager;
  34158. })(BABYLON || (BABYLON = {}));
  34159. //# sourceMappingURL=babylon.postProcessManager.js.map
  34160. var BABYLON;
  34161. (function (BABYLON) {
  34162. /**
  34163. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34164. */
  34165. var PerformanceMonitor = /** @class */ (function () {
  34166. /**
  34167. * constructor
  34168. * @param frameSampleSize The number of samples required to saturate the sliding window
  34169. */
  34170. function PerformanceMonitor(frameSampleSize) {
  34171. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34172. this._enabled = true;
  34173. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34174. }
  34175. /**
  34176. * Samples current frame
  34177. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34178. */
  34179. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34180. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34181. if (!this._enabled)
  34182. return;
  34183. if (this._lastFrameTimeMs != null) {
  34184. var dt = timeMs - this._lastFrameTimeMs;
  34185. this._rollingFrameTime.add(dt);
  34186. }
  34187. this._lastFrameTimeMs = timeMs;
  34188. };
  34189. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34190. /**
  34191. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34192. * @return Average frame time in milliseconds
  34193. */
  34194. get: function () {
  34195. return this._rollingFrameTime.average;
  34196. },
  34197. enumerable: true,
  34198. configurable: true
  34199. });
  34200. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34201. /**
  34202. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34203. * @return Frame time variance in milliseconds squared
  34204. */
  34205. get: function () {
  34206. return this._rollingFrameTime.variance;
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34212. /**
  34213. * Returns the frame time of the most recent frame
  34214. * @return Frame time in milliseconds
  34215. */
  34216. get: function () {
  34217. return this._rollingFrameTime.history(0);
  34218. },
  34219. enumerable: true,
  34220. configurable: true
  34221. });
  34222. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34223. /**
  34224. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34225. * @return Framerate in frames per second
  34226. */
  34227. get: function () {
  34228. return 1000.0 / this._rollingFrameTime.average;
  34229. },
  34230. enumerable: true,
  34231. configurable: true
  34232. });
  34233. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34234. /**
  34235. * Returns the average framerate in frames per second using the most recent frame time
  34236. * @return Framerate in frames per second
  34237. */
  34238. get: function () {
  34239. var history = this._rollingFrameTime.history(0);
  34240. if (history === 0) {
  34241. return 0;
  34242. }
  34243. return 1000.0 / history;
  34244. },
  34245. enumerable: true,
  34246. configurable: true
  34247. });
  34248. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34249. /**
  34250. * Returns true if enough samples have been taken to completely fill the sliding window
  34251. * @return true if saturated
  34252. */
  34253. get: function () {
  34254. return this._rollingFrameTime.isSaturated();
  34255. },
  34256. enumerable: true,
  34257. configurable: true
  34258. });
  34259. /**
  34260. * Enables contributions to the sliding window sample set
  34261. */
  34262. PerformanceMonitor.prototype.enable = function () {
  34263. this._enabled = true;
  34264. };
  34265. /**
  34266. * Disables contributions to the sliding window sample set
  34267. * Samples will not be interpolated over the disabled period
  34268. */
  34269. PerformanceMonitor.prototype.disable = function () {
  34270. this._enabled = false;
  34271. //clear last sample to avoid interpolating over the disabled period when next enabled
  34272. this._lastFrameTimeMs = null;
  34273. };
  34274. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34275. /**
  34276. * Returns true if sampling is enabled
  34277. * @return true if enabled
  34278. */
  34279. get: function () {
  34280. return this._enabled;
  34281. },
  34282. enumerable: true,
  34283. configurable: true
  34284. });
  34285. /**
  34286. * Resets performance monitor
  34287. */
  34288. PerformanceMonitor.prototype.reset = function () {
  34289. //clear last sample to avoid interpolating over the disabled period when next enabled
  34290. this._lastFrameTimeMs = null;
  34291. //wipe record
  34292. this._rollingFrameTime.reset();
  34293. };
  34294. return PerformanceMonitor;
  34295. }());
  34296. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34297. /**
  34298. * RollingAverage
  34299. *
  34300. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34301. */
  34302. var RollingAverage = /** @class */ (function () {
  34303. /**
  34304. * constructor
  34305. * @param length The number of samples required to saturate the sliding window
  34306. */
  34307. function RollingAverage(length) {
  34308. this._samples = new Array(length);
  34309. this.reset();
  34310. }
  34311. /**
  34312. * Adds a sample to the sample set
  34313. * @param v The sample value
  34314. */
  34315. RollingAverage.prototype.add = function (v) {
  34316. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34317. var delta;
  34318. //we need to check if we've already wrapped round
  34319. if (this.isSaturated()) {
  34320. //remove bottom of stack from mean
  34321. var bottomValue = this._samples[this._pos];
  34322. delta = bottomValue - this.average;
  34323. this.average -= delta / (this._sampleCount - 1);
  34324. this._m2 -= delta * (bottomValue - this.average);
  34325. }
  34326. else {
  34327. this._sampleCount++;
  34328. }
  34329. //add new value to mean
  34330. delta = v - this.average;
  34331. this.average += delta / (this._sampleCount);
  34332. this._m2 += delta * (v - this.average);
  34333. //set the new variance
  34334. this.variance = this._m2 / (this._sampleCount - 1);
  34335. this._samples[this._pos] = v;
  34336. this._pos++;
  34337. this._pos %= this._samples.length; //positive wrap around
  34338. };
  34339. /**
  34340. * Returns previously added values or null if outside of history or outside the sliding window domain
  34341. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34342. * @return Value previously recorded with add() or null if outside of range
  34343. */
  34344. RollingAverage.prototype.history = function (i) {
  34345. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34346. return 0;
  34347. }
  34348. var i0 = this._wrapPosition(this._pos - 1.0);
  34349. return this._samples[this._wrapPosition(i0 - i)];
  34350. };
  34351. /**
  34352. * Returns true if enough samples have been taken to completely fill the sliding window
  34353. * @return true if sample-set saturated
  34354. */
  34355. RollingAverage.prototype.isSaturated = function () {
  34356. return this._sampleCount >= this._samples.length;
  34357. };
  34358. /**
  34359. * Resets the rolling average (equivalent to 0 samples taken so far)
  34360. */
  34361. RollingAverage.prototype.reset = function () {
  34362. this.average = 0;
  34363. this.variance = 0;
  34364. this._sampleCount = 0;
  34365. this._pos = 0;
  34366. this._m2 = 0;
  34367. };
  34368. /**
  34369. * Wraps a value around the sample range boundaries
  34370. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34371. * @return Wrapped position in sample range
  34372. */
  34373. RollingAverage.prototype._wrapPosition = function (i) {
  34374. var max = this._samples.length;
  34375. return ((i % max) + max) % max;
  34376. };
  34377. return RollingAverage;
  34378. }());
  34379. BABYLON.RollingAverage = RollingAverage;
  34380. })(BABYLON || (BABYLON = {}));
  34381. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34382. var BABYLON;
  34383. (function (BABYLON) {
  34384. /**
  34385. * This groups together the common properties used for image processing either in direct forward pass
  34386. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34387. * or not.
  34388. */
  34389. var ImageProcessingConfiguration = /** @class */ (function () {
  34390. function ImageProcessingConfiguration() {
  34391. /**
  34392. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34393. */
  34394. this.colorCurves = new BABYLON.ColorCurves();
  34395. this._colorCurvesEnabled = false;
  34396. this._colorGradingEnabled = false;
  34397. this._colorGradingWithGreenDepth = true;
  34398. this._colorGradingBGR = true;
  34399. this._exposure = 1.0;
  34400. this._toneMappingEnabled = false;
  34401. this._contrast = 1.0;
  34402. /**
  34403. * Vignette stretch size.
  34404. */
  34405. this.vignetteStretch = 0;
  34406. /**
  34407. * Vignette centre X Offset.
  34408. */
  34409. this.vignetteCentreX = 0;
  34410. /**
  34411. * Vignette centre Y Offset.
  34412. */
  34413. this.vignetteCentreY = 0;
  34414. /**
  34415. * Vignette weight or intensity of the vignette effect.
  34416. */
  34417. this.vignetteWeight = 1.5;
  34418. /**
  34419. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34420. * if vignetteEnabled is set to true.
  34421. */
  34422. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34423. /**
  34424. * Camera field of view used by the Vignette effect.
  34425. */
  34426. this.vignetteCameraFov = 0.5;
  34427. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34428. this._vignetteEnabled = false;
  34429. this._applyByPostProcess = false;
  34430. this._isEnabled = true;
  34431. /**
  34432. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34433. * @type {BABYLON.Observable}
  34434. */
  34435. this.onUpdateParameters = new BABYLON.Observable();
  34436. }
  34437. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34438. /**
  34439. * Gets wether the color curves effect is enabled.
  34440. */
  34441. get: function () {
  34442. return this._colorCurvesEnabled;
  34443. },
  34444. /**
  34445. * Sets wether the color curves effect is enabled.
  34446. */
  34447. set: function (value) {
  34448. if (this._colorCurvesEnabled === value) {
  34449. return;
  34450. }
  34451. this._colorCurvesEnabled = value;
  34452. this._updateParameters();
  34453. },
  34454. enumerable: true,
  34455. configurable: true
  34456. });
  34457. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34458. /**
  34459. * Gets wether the color grading effect is enabled.
  34460. */
  34461. get: function () {
  34462. return this._colorGradingEnabled;
  34463. },
  34464. /**
  34465. * Sets wether the color grading effect is enabled.
  34466. */
  34467. set: function (value) {
  34468. if (this._colorGradingEnabled === value) {
  34469. return;
  34470. }
  34471. this._colorGradingEnabled = value;
  34472. this._updateParameters();
  34473. },
  34474. enumerable: true,
  34475. configurable: true
  34476. });
  34477. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34478. /**
  34479. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34480. */
  34481. get: function () {
  34482. return this._colorGradingWithGreenDepth;
  34483. },
  34484. /**
  34485. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34486. */
  34487. set: function (value) {
  34488. if (this._colorGradingWithGreenDepth === value) {
  34489. return;
  34490. }
  34491. this._colorGradingWithGreenDepth = value;
  34492. this._updateParameters();
  34493. },
  34494. enumerable: true,
  34495. configurable: true
  34496. });
  34497. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34498. /**
  34499. * Gets wether the color grading texture contains BGR values.
  34500. */
  34501. get: function () {
  34502. return this._colorGradingBGR;
  34503. },
  34504. /**
  34505. * Sets wether the color grading texture contains BGR values.
  34506. */
  34507. set: function (value) {
  34508. if (this._colorGradingBGR === value) {
  34509. return;
  34510. }
  34511. this._colorGradingBGR = value;
  34512. this._updateParameters();
  34513. },
  34514. enumerable: true,
  34515. configurable: true
  34516. });
  34517. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34518. /**
  34519. * Gets the Exposure used in the effect.
  34520. */
  34521. get: function () {
  34522. return this._exposure;
  34523. },
  34524. /**
  34525. * Sets the Exposure used in the effect.
  34526. */
  34527. set: function (value) {
  34528. if (this._exposure === value) {
  34529. return;
  34530. }
  34531. this._exposure = value;
  34532. this._updateParameters();
  34533. },
  34534. enumerable: true,
  34535. configurable: true
  34536. });
  34537. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34538. /**
  34539. * Gets wether the tone mapping effect is enabled.
  34540. */
  34541. get: function () {
  34542. return this._toneMappingEnabled;
  34543. },
  34544. /**
  34545. * Sets wether the tone mapping effect is enabled.
  34546. */
  34547. set: function (value) {
  34548. if (this._toneMappingEnabled === value) {
  34549. return;
  34550. }
  34551. this._toneMappingEnabled = value;
  34552. this._updateParameters();
  34553. },
  34554. enumerable: true,
  34555. configurable: true
  34556. });
  34557. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34558. /**
  34559. * Gets the contrast used in the effect.
  34560. */
  34561. get: function () {
  34562. return this._contrast;
  34563. },
  34564. /**
  34565. * Sets the contrast used in the effect.
  34566. */
  34567. set: function (value) {
  34568. if (this._contrast === value) {
  34569. return;
  34570. }
  34571. this._contrast = value;
  34572. this._updateParameters();
  34573. },
  34574. enumerable: true,
  34575. configurable: true
  34576. });
  34577. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34578. /**
  34579. * Gets the vignette blend mode allowing different kind of effect.
  34580. */
  34581. get: function () {
  34582. return this._vignetteBlendMode;
  34583. },
  34584. /**
  34585. * Sets the vignette blend mode allowing different kind of effect.
  34586. */
  34587. set: function (value) {
  34588. if (this._vignetteBlendMode === value) {
  34589. return;
  34590. }
  34591. this._vignetteBlendMode = value;
  34592. this._updateParameters();
  34593. },
  34594. enumerable: true,
  34595. configurable: true
  34596. });
  34597. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34598. /**
  34599. * Gets wether the vignette effect is enabled.
  34600. */
  34601. get: function () {
  34602. return this._vignetteEnabled;
  34603. },
  34604. /**
  34605. * Sets wether the vignette effect is enabled.
  34606. */
  34607. set: function (value) {
  34608. if (this._vignetteEnabled === value) {
  34609. return;
  34610. }
  34611. this._vignetteEnabled = value;
  34612. this._updateParameters();
  34613. },
  34614. enumerable: true,
  34615. configurable: true
  34616. });
  34617. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34618. /**
  34619. * Gets wether the image processing is applied through a post process or not.
  34620. */
  34621. get: function () {
  34622. return this._applyByPostProcess;
  34623. },
  34624. /**
  34625. * Sets wether the image processing is applied through a post process or not.
  34626. */
  34627. set: function (value) {
  34628. if (this._applyByPostProcess === value) {
  34629. return;
  34630. }
  34631. this._applyByPostProcess = value;
  34632. this._updateParameters();
  34633. },
  34634. enumerable: true,
  34635. configurable: true
  34636. });
  34637. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34638. /**
  34639. * Gets wether the image processing is enabled or not.
  34640. */
  34641. get: function () {
  34642. return this._isEnabled;
  34643. },
  34644. /**
  34645. * Sets wether the image processing is enabled or not.
  34646. */
  34647. set: function (value) {
  34648. if (this._isEnabled === value) {
  34649. return;
  34650. }
  34651. this._isEnabled = value;
  34652. this._updateParameters();
  34653. },
  34654. enumerable: true,
  34655. configurable: true
  34656. });
  34657. /**
  34658. * Method called each time the image processing information changes requires to recompile the effect.
  34659. */
  34660. ImageProcessingConfiguration.prototype._updateParameters = function () {
  34661. this.onUpdateParameters.notifyObservers(this);
  34662. };
  34663. ImageProcessingConfiguration.prototype.getClassName = function () {
  34664. return "ImageProcessingConfiguration";
  34665. };
  34666. /**
  34667. * Prepare the list of uniforms associated with the Image Processing effects.
  34668. * @param uniformsList The list of uniforms used in the effect
  34669. * @param defines the list of defines currently in use
  34670. */
  34671. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  34672. if (defines.EXPOSURE) {
  34673. uniforms.push("exposureLinear");
  34674. }
  34675. if (defines.CONTRAST) {
  34676. uniforms.push("contrast");
  34677. }
  34678. if (defines.COLORGRADING) {
  34679. uniforms.push("colorTransformSettings");
  34680. }
  34681. if (defines.VIGNETTE) {
  34682. uniforms.push("vInverseScreenSize");
  34683. uniforms.push("vignetteSettings1");
  34684. uniforms.push("vignetteSettings2");
  34685. }
  34686. if (defines.COLORCURVES) {
  34687. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  34688. }
  34689. };
  34690. /**
  34691. * Prepare the list of samplers associated with the Image Processing effects.
  34692. * @param uniformsList The list of uniforms used in the effect
  34693. * @param defines the list of defines currently in use
  34694. */
  34695. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  34696. if (defines.COLORGRADING) {
  34697. samplersList.push("txColorTransform");
  34698. }
  34699. };
  34700. /**
  34701. * Prepare the list of defines associated to the shader.
  34702. * @param defines the list of defines to complete
  34703. */
  34704. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  34705. if (forPostProcess === void 0) { forPostProcess = false; }
  34706. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  34707. defines.VIGNETTE = false;
  34708. defines.TONEMAPPING = false;
  34709. defines.CONTRAST = false;
  34710. defines.EXPOSURE = false;
  34711. defines.COLORCURVES = false;
  34712. defines.COLORGRADING = false;
  34713. defines.COLORGRADING3D = false;
  34714. defines.IMAGEPROCESSING = false;
  34715. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  34716. return;
  34717. }
  34718. defines.VIGNETTE = this.vignetteEnabled;
  34719. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  34720. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  34721. defines.TONEMAPPING = this.toneMappingEnabled;
  34722. defines.CONTRAST = (this.contrast !== 1.0);
  34723. defines.EXPOSURE = (this.exposure !== 1.0);
  34724. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  34725. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  34726. if (defines.COLORGRADING) {
  34727. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  34728. }
  34729. else {
  34730. defines.COLORGRADING3D = false;
  34731. }
  34732. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  34733. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  34734. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  34735. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  34736. };
  34737. /**
  34738. * Returns true if all the image processing information are ready.
  34739. */
  34740. ImageProcessingConfiguration.prototype.isReady = function () {
  34741. // Color Grading texure can not be none blocking.
  34742. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  34743. };
  34744. /**
  34745. * Binds the image processing to the shader.
  34746. * @param effect The effect to bind to
  34747. */
  34748. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  34749. if (aspectRatio === void 0) { aspectRatio = 1; }
  34750. // Color Curves
  34751. if (this._colorCurvesEnabled && this.colorCurves) {
  34752. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  34753. }
  34754. // Vignette
  34755. if (this._vignetteEnabled) {
  34756. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  34757. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  34758. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  34759. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  34760. var vignetteScaleX = vignetteScaleY * aspectRatio;
  34761. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  34762. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  34763. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  34764. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  34765. var vignettePower = -2.0 * this.vignetteWeight;
  34766. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  34767. }
  34768. // Exposure
  34769. effect.setFloat("exposureLinear", this.exposure);
  34770. // Contrast
  34771. effect.setFloat("contrast", this.contrast);
  34772. // Color transform settings
  34773. if (this.colorGradingTexture) {
  34774. effect.setTexture("txColorTransform", this.colorGradingTexture);
  34775. var textureSize = this.colorGradingTexture.getSize().height;
  34776. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  34777. 0.5 / textureSize, // textureOffset
  34778. textureSize, // textureSize
  34779. this.colorGradingTexture.level // weight
  34780. );
  34781. }
  34782. };
  34783. /**
  34784. * Clones the current image processing instance.
  34785. * @return The cloned image processing
  34786. */
  34787. ImageProcessingConfiguration.prototype.clone = function () {
  34788. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  34789. };
  34790. /**
  34791. * Serializes the current image processing instance to a json representation.
  34792. * @return a JSON representation
  34793. */
  34794. ImageProcessingConfiguration.prototype.serialize = function () {
  34795. return BABYLON.SerializationHelper.Serialize(this);
  34796. };
  34797. /**
  34798. * Parses the image processing from a json representation.
  34799. * @param source the JSON source to parse
  34800. * @return The parsed image processing
  34801. */
  34802. ImageProcessingConfiguration.Parse = function (source) {
  34803. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  34804. };
  34805. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  34806. /**
  34807. * Used to apply the vignette as a mix with the pixel color.
  34808. */
  34809. get: function () {
  34810. return this._VIGNETTEMODE_MULTIPLY;
  34811. },
  34812. enumerable: true,
  34813. configurable: true
  34814. });
  34815. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  34816. /**
  34817. * Used to apply the vignette as a replacement of the pixel color.
  34818. */
  34819. get: function () {
  34820. return this._VIGNETTEMODE_OPAQUE;
  34821. },
  34822. enumerable: true,
  34823. configurable: true
  34824. });
  34825. // Static constants associated to the image processing.
  34826. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  34827. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  34828. __decorate([
  34829. BABYLON.serializeAsColorCurves()
  34830. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  34831. __decorate([
  34832. BABYLON.serialize()
  34833. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  34834. __decorate([
  34835. BABYLON.serializeAsTexture()
  34836. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  34837. __decorate([
  34838. BABYLON.serialize()
  34839. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  34840. __decorate([
  34841. BABYLON.serialize()
  34842. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  34843. __decorate([
  34844. BABYLON.serialize()
  34845. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  34846. __decorate([
  34847. BABYLON.serialize()
  34848. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  34849. __decorate([
  34850. BABYLON.serialize()
  34851. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  34852. __decorate([
  34853. BABYLON.serialize()
  34854. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  34855. __decorate([
  34856. BABYLON.serialize()
  34857. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  34858. __decorate([
  34859. BABYLON.serialize()
  34860. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  34861. __decorate([
  34862. BABYLON.serialize()
  34863. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  34864. __decorate([
  34865. BABYLON.serialize()
  34866. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  34867. __decorate([
  34868. BABYLON.serializeAsColor4()
  34869. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  34870. __decorate([
  34871. BABYLON.serialize()
  34872. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  34873. __decorate([
  34874. BABYLON.serialize()
  34875. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  34876. __decorate([
  34877. BABYLON.serialize()
  34878. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  34879. __decorate([
  34880. BABYLON.serialize()
  34881. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  34882. __decorate([
  34883. BABYLON.serialize()
  34884. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  34885. return ImageProcessingConfiguration;
  34886. }());
  34887. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  34888. })(BABYLON || (BABYLON = {}));
  34889. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  34890. var BABYLON;
  34891. (function (BABYLON) {
  34892. /**
  34893. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  34894. * It can help converting any input color in a desired output one. This can then be used to create effects
  34895. * from sepia, black and white to sixties or futuristic rendering...
  34896. *
  34897. * The only supported format is currently 3dl.
  34898. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  34899. */
  34900. var ColorGradingTexture = /** @class */ (function (_super) {
  34901. __extends(ColorGradingTexture, _super);
  34902. /**
  34903. * Instantiates a ColorGradingTexture from the following parameters.
  34904. *
  34905. * @param url The location of the color gradind data (currently only supporting 3dl)
  34906. * @param scene The scene the texture will be used in
  34907. */
  34908. function ColorGradingTexture(url, scene) {
  34909. var _this = _super.call(this, scene) || this;
  34910. if (!url) {
  34911. return _this;
  34912. }
  34913. _this._engine = scene.getEngine();
  34914. _this._textureMatrix = BABYLON.Matrix.Identity();
  34915. _this.name = url;
  34916. _this.url = url;
  34917. _this.hasAlpha = false;
  34918. _this.isCube = false;
  34919. _this.is3D = _this._engine.webGLVersion > 1;
  34920. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34921. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34922. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34923. _this.anisotropicFilteringLevel = 1;
  34924. _this._texture = _this._getFromCache(url, true);
  34925. if (!_this._texture) {
  34926. if (!scene.useDelayedTextureLoading) {
  34927. _this.loadTexture();
  34928. }
  34929. else {
  34930. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34931. }
  34932. }
  34933. return _this;
  34934. }
  34935. /**
  34936. * Returns the texture matrix used in most of the material.
  34937. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  34938. */
  34939. ColorGradingTexture.prototype.getTextureMatrix = function () {
  34940. return this._textureMatrix;
  34941. };
  34942. /**
  34943. * Occurs when the file being loaded is a .3dl LUT file.
  34944. */
  34945. ColorGradingTexture.prototype.load3dlTexture = function () {
  34946. var engine = this._engine;
  34947. var texture;
  34948. if (engine.webGLVersion === 1) {
  34949. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34950. }
  34951. else {
  34952. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34953. }
  34954. this._texture = texture;
  34955. var callback = function (text) {
  34956. if (typeof text !== "string") {
  34957. return;
  34958. }
  34959. var data = null;
  34960. var tempData = null;
  34961. var line;
  34962. var lines = text.split('\n');
  34963. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  34964. var maxColor = 0;
  34965. for (var i = 0; i < lines.length; i++) {
  34966. line = lines[i];
  34967. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  34968. continue;
  34969. if (line.indexOf('#') === 0)
  34970. continue;
  34971. var words = line.split(" ");
  34972. if (size === 0) {
  34973. // Number of space + one
  34974. size = words.length;
  34975. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  34976. tempData = new Float32Array(size * size * size * 4);
  34977. continue;
  34978. }
  34979. if (size != 0) {
  34980. var r = Math.max(parseInt(words[0]), 0);
  34981. var g = Math.max(parseInt(words[1]), 0);
  34982. var b = Math.max(parseInt(words[2]), 0);
  34983. maxColor = Math.max(r, maxColor);
  34984. maxColor = Math.max(g, maxColor);
  34985. maxColor = Math.max(b, maxColor);
  34986. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  34987. if (tempData) {
  34988. tempData[pixelStorageIndex + 0] = r;
  34989. tempData[pixelStorageIndex + 1] = g;
  34990. tempData[pixelStorageIndex + 2] = b;
  34991. }
  34992. pixelIndexSlice++;
  34993. if (pixelIndexSlice % size == 0) {
  34994. pixelIndexH++;
  34995. pixelIndexSlice = 0;
  34996. if (pixelIndexH % size == 0) {
  34997. pixelIndexW++;
  34998. pixelIndexH = 0;
  34999. }
  35000. }
  35001. }
  35002. }
  35003. if (tempData && data) {
  35004. for (var i = 0; i < tempData.length; i++) {
  35005. if (i > 0 && (i + 1) % 4 === 0) {
  35006. data[i] = 255;
  35007. }
  35008. else {
  35009. var value = tempData[i];
  35010. data[i] = (value / maxColor * 255);
  35011. }
  35012. }
  35013. }
  35014. if (texture.is3D) {
  35015. texture.updateSize(size, size, size);
  35016. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35017. }
  35018. else {
  35019. texture.updateSize(size * size, size);
  35020. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35021. }
  35022. };
  35023. var scene = this.getScene();
  35024. if (scene) {
  35025. scene._loadFile(this.url, callback);
  35026. }
  35027. else {
  35028. this._engine._loadFile(this.url, callback);
  35029. }
  35030. return this._texture;
  35031. };
  35032. /**
  35033. * Starts the loading process of the texture.
  35034. */
  35035. ColorGradingTexture.prototype.loadTexture = function () {
  35036. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35037. this.load3dlTexture();
  35038. }
  35039. };
  35040. /**
  35041. * Clones the color gradind texture.
  35042. */
  35043. ColorGradingTexture.prototype.clone = function () {
  35044. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35045. // Base texture
  35046. newTexture.level = this.level;
  35047. return newTexture;
  35048. };
  35049. /**
  35050. * Called during delayed load for textures.
  35051. */
  35052. ColorGradingTexture.prototype.delayLoad = function () {
  35053. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35054. return;
  35055. }
  35056. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35057. this._texture = this._getFromCache(this.url, true);
  35058. if (!this._texture) {
  35059. this.loadTexture();
  35060. }
  35061. };
  35062. /**
  35063. * Parses a color grading texture serialized by Babylon.
  35064. * @param parsedTexture The texture information being parsedTexture
  35065. * @param scene The scene to load the texture in
  35066. * @param rootUrl The root url of the data assets to load
  35067. * @return A color gradind texture
  35068. */
  35069. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35070. var texture = null;
  35071. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35072. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35073. texture.name = parsedTexture.name;
  35074. texture.level = parsedTexture.level;
  35075. }
  35076. return texture;
  35077. };
  35078. /**
  35079. * Serializes the LUT texture to json format.
  35080. */
  35081. ColorGradingTexture.prototype.serialize = function () {
  35082. if (!this.name) {
  35083. return null;
  35084. }
  35085. var serializationObject = {};
  35086. serializationObject.name = this.name;
  35087. serializationObject.level = this.level;
  35088. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35089. return serializationObject;
  35090. };
  35091. /**
  35092. * Empty line regex stored for GC.
  35093. */
  35094. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35095. return ColorGradingTexture;
  35096. }(BABYLON.BaseTexture));
  35097. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35098. })(BABYLON || (BABYLON = {}));
  35099. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35100. var BABYLON;
  35101. (function (BABYLON) {
  35102. /**
  35103. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35104. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35105. * 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;
  35106. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35107. */
  35108. var ColorCurves = /** @class */ (function () {
  35109. function ColorCurves() {
  35110. this._dirty = true;
  35111. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35112. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35113. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35114. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35115. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35116. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35117. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35118. this._globalHue = 30;
  35119. this._globalDensity = 0;
  35120. this._globalSaturation = 0;
  35121. this._globalExposure = 0;
  35122. this._highlightsHue = 30;
  35123. this._highlightsDensity = 0;
  35124. this._highlightsSaturation = 0;
  35125. this._highlightsExposure = 0;
  35126. this._midtonesHue = 30;
  35127. this._midtonesDensity = 0;
  35128. this._midtonesSaturation = 0;
  35129. this._midtonesExposure = 0;
  35130. this._shadowsHue = 30;
  35131. this._shadowsDensity = 0;
  35132. this._shadowsSaturation = 0;
  35133. this._shadowsExposure = 0;
  35134. }
  35135. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35136. /**
  35137. * Gets the global Hue value.
  35138. * 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).
  35139. */
  35140. get: function () {
  35141. return this._globalHue;
  35142. },
  35143. /**
  35144. * Sets the global Hue value.
  35145. * 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).
  35146. */
  35147. set: function (value) {
  35148. this._globalHue = value;
  35149. this._dirty = true;
  35150. },
  35151. enumerable: true,
  35152. configurable: true
  35153. });
  35154. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35155. /**
  35156. * Gets the global Density value.
  35157. * 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.
  35158. * Values less than zero provide a filter of opposite hue.
  35159. */
  35160. get: function () {
  35161. return this._globalDensity;
  35162. },
  35163. /**
  35164. * Sets the global Density value.
  35165. * 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.
  35166. * Values less than zero provide a filter of opposite hue.
  35167. */
  35168. set: function (value) {
  35169. this._globalDensity = value;
  35170. this._dirty = true;
  35171. },
  35172. enumerable: true,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35176. /**
  35177. * Gets the global Saturation value.
  35178. * 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.
  35179. */
  35180. get: function () {
  35181. return this._globalSaturation;
  35182. },
  35183. /**
  35184. * Sets the global Saturation value.
  35185. * 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.
  35186. */
  35187. set: function (value) {
  35188. this._globalSaturation = value;
  35189. this._dirty = true;
  35190. },
  35191. enumerable: true,
  35192. configurable: true
  35193. });
  35194. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35195. /**
  35196. * Gets the highlights Hue value.
  35197. * 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).
  35198. */
  35199. get: function () {
  35200. return this._highlightsHue;
  35201. },
  35202. /**
  35203. * Sets the highlights Hue value.
  35204. * 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).
  35205. */
  35206. set: function (value) {
  35207. this._highlightsHue = value;
  35208. this._dirty = true;
  35209. },
  35210. enumerable: true,
  35211. configurable: true
  35212. });
  35213. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35214. /**
  35215. * Gets the highlights Density value.
  35216. * 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.
  35217. * Values less than zero provide a filter of opposite hue.
  35218. */
  35219. get: function () {
  35220. return this._highlightsDensity;
  35221. },
  35222. /**
  35223. * Sets the highlights Density value.
  35224. * 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.
  35225. * Values less than zero provide a filter of opposite hue.
  35226. */
  35227. set: function (value) {
  35228. this._highlightsDensity = value;
  35229. this._dirty = true;
  35230. },
  35231. enumerable: true,
  35232. configurable: true
  35233. });
  35234. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35235. /**
  35236. * Gets the highlights Saturation value.
  35237. * 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.
  35238. */
  35239. get: function () {
  35240. return this._highlightsSaturation;
  35241. },
  35242. /**
  35243. * Sets the highlights Saturation value.
  35244. * 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.
  35245. */
  35246. set: function (value) {
  35247. this._highlightsSaturation = value;
  35248. this._dirty = true;
  35249. },
  35250. enumerable: true,
  35251. configurable: true
  35252. });
  35253. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35254. /**
  35255. * Gets the highlights Exposure value.
  35256. * 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.
  35257. */
  35258. get: function () {
  35259. return this._highlightsExposure;
  35260. },
  35261. /**
  35262. * Sets the highlights Exposure value.
  35263. * 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.
  35264. */
  35265. set: function (value) {
  35266. this._highlightsExposure = value;
  35267. this._dirty = true;
  35268. },
  35269. enumerable: true,
  35270. configurable: true
  35271. });
  35272. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35273. /**
  35274. * Gets the midtones Hue value.
  35275. * 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).
  35276. */
  35277. get: function () {
  35278. return this._midtonesHue;
  35279. },
  35280. /**
  35281. * Sets the midtones Hue value.
  35282. * 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).
  35283. */
  35284. set: function (value) {
  35285. this._midtonesHue = value;
  35286. this._dirty = true;
  35287. },
  35288. enumerable: true,
  35289. configurable: true
  35290. });
  35291. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35292. /**
  35293. * Gets the midtones Density value.
  35294. * 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.
  35295. * Values less than zero provide a filter of opposite hue.
  35296. */
  35297. get: function () {
  35298. return this._midtonesDensity;
  35299. },
  35300. /**
  35301. * Sets the midtones Density value.
  35302. * 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.
  35303. * Values less than zero provide a filter of opposite hue.
  35304. */
  35305. set: function (value) {
  35306. this._midtonesDensity = value;
  35307. this._dirty = true;
  35308. },
  35309. enumerable: true,
  35310. configurable: true
  35311. });
  35312. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35313. /**
  35314. * Gets the midtones Saturation value.
  35315. * 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.
  35316. */
  35317. get: function () {
  35318. return this._midtonesSaturation;
  35319. },
  35320. /**
  35321. * Sets the midtones Saturation value.
  35322. * 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.
  35323. */
  35324. set: function (value) {
  35325. this._midtonesSaturation = value;
  35326. this._dirty = true;
  35327. },
  35328. enumerable: true,
  35329. configurable: true
  35330. });
  35331. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35332. /**
  35333. * Gets the midtones Exposure value.
  35334. * 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.
  35335. */
  35336. get: function () {
  35337. return this._midtonesExposure;
  35338. },
  35339. /**
  35340. * Sets the midtones Exposure value.
  35341. * 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.
  35342. */
  35343. set: function (value) {
  35344. this._midtonesExposure = value;
  35345. this._dirty = true;
  35346. },
  35347. enumerable: true,
  35348. configurable: true
  35349. });
  35350. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35351. /**
  35352. * Gets the shadows Hue value.
  35353. * 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).
  35354. */
  35355. get: function () {
  35356. return this._shadowsHue;
  35357. },
  35358. /**
  35359. * Sets the shadows Hue value.
  35360. * 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).
  35361. */
  35362. set: function (value) {
  35363. this._shadowsHue = value;
  35364. this._dirty = true;
  35365. },
  35366. enumerable: true,
  35367. configurable: true
  35368. });
  35369. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35370. /**
  35371. * Gets the shadows Density value.
  35372. * 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.
  35373. * Values less than zero provide a filter of opposite hue.
  35374. */
  35375. get: function () {
  35376. return this._shadowsDensity;
  35377. },
  35378. /**
  35379. * Sets the shadows Density value.
  35380. * 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.
  35381. * Values less than zero provide a filter of opposite hue.
  35382. */
  35383. set: function (value) {
  35384. this._shadowsDensity = value;
  35385. this._dirty = true;
  35386. },
  35387. enumerable: true,
  35388. configurable: true
  35389. });
  35390. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35391. /**
  35392. * Gets the shadows Saturation value.
  35393. * 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.
  35394. */
  35395. get: function () {
  35396. return this._shadowsSaturation;
  35397. },
  35398. /**
  35399. * Sets the shadows Saturation value.
  35400. * 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.
  35401. */
  35402. set: function (value) {
  35403. this._shadowsSaturation = value;
  35404. this._dirty = true;
  35405. },
  35406. enumerable: true,
  35407. configurable: true
  35408. });
  35409. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35410. /**
  35411. * Gets the shadows Exposure value.
  35412. * 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.
  35413. */
  35414. get: function () {
  35415. return this._shadowsExposure;
  35416. },
  35417. /**
  35418. * Sets the shadows Exposure value.
  35419. * 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.
  35420. */
  35421. set: function (value) {
  35422. this._shadowsExposure = value;
  35423. this._dirty = true;
  35424. },
  35425. enumerable: true,
  35426. configurable: true
  35427. });
  35428. ColorCurves.prototype.getClassName = function () {
  35429. return "ColorCurves";
  35430. };
  35431. /**
  35432. * Binds the color curves to the shader.
  35433. * @param colorCurves The color curve to bind
  35434. * @param effect The effect to bind to
  35435. */
  35436. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35437. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35438. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35439. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35440. if (colorCurves._dirty) {
  35441. colorCurves._dirty = false;
  35442. // Fill in global info.
  35443. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35444. // Compute highlights info.
  35445. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35446. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35447. // Compute midtones info.
  35448. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35449. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35450. // Compute shadows info.
  35451. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35452. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35453. // Compute deltas (neutral is midtones).
  35454. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35455. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35456. }
  35457. if (effect) {
  35458. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35459. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35460. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35461. }
  35462. };
  35463. /**
  35464. * Prepare the list of uniforms associated with the ColorCurves effects.
  35465. * @param uniformsList The list of uniforms used in the effect
  35466. */
  35467. ColorCurves.PrepareUniforms = function (uniformsList) {
  35468. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35469. };
  35470. /**
  35471. * Returns color grading data based on a hue, density, saturation and exposure value.
  35472. * @param filterHue The hue of the color filter.
  35473. * @param filterDensity The density of the color filter.
  35474. * @param saturation The saturation.
  35475. * @param exposure The exposure.
  35476. * @param result The result data container.
  35477. */
  35478. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35479. if (hue == null) {
  35480. return;
  35481. }
  35482. hue = ColorCurves.clamp(hue, 0, 360);
  35483. density = ColorCurves.clamp(density, -100, 100);
  35484. saturation = ColorCurves.clamp(saturation, -100, 100);
  35485. exposure = ColorCurves.clamp(exposure, -100, 100);
  35486. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35487. // so that the maximum filter density is only 50% control. This provides fine control
  35488. // for small values and reasonable range.
  35489. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35490. density *= 0.5;
  35491. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35492. if (density < 0) {
  35493. density *= -1;
  35494. hue = (hue + 180) % 360;
  35495. }
  35496. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35497. result.scaleToRef(2, result);
  35498. result.a = 1 + 0.01 * saturation;
  35499. };
  35500. /**
  35501. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35502. * @param value The input slider value in range [-100,100].
  35503. * @returns Adjusted value.
  35504. */
  35505. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35506. value /= 100;
  35507. var x = Math.abs(value);
  35508. x = Math.pow(x, 2);
  35509. if (value < 0) {
  35510. x *= -1;
  35511. }
  35512. x *= 100;
  35513. return x;
  35514. };
  35515. /**
  35516. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35517. * @param hue The hue (H) input.
  35518. * @param saturation The saturation (S) input.
  35519. * @param brightness The brightness (B) input.
  35520. * @result An RGBA color represented as Vector4.
  35521. */
  35522. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35523. var h = ColorCurves.clamp(hue, 0, 360);
  35524. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35525. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35526. if (s === 0) {
  35527. result.r = v;
  35528. result.g = v;
  35529. result.b = v;
  35530. }
  35531. else {
  35532. // sector 0 to 5
  35533. h /= 60;
  35534. var i = Math.floor(h);
  35535. // fractional part of h
  35536. var f = h - i;
  35537. var p = v * (1 - s);
  35538. var q = v * (1 - s * f);
  35539. var t = v * (1 - s * (1 - f));
  35540. switch (i) {
  35541. case 0:
  35542. result.r = v;
  35543. result.g = t;
  35544. result.b = p;
  35545. break;
  35546. case 1:
  35547. result.r = q;
  35548. result.g = v;
  35549. result.b = p;
  35550. break;
  35551. case 2:
  35552. result.r = p;
  35553. result.g = v;
  35554. result.b = t;
  35555. break;
  35556. case 3:
  35557. result.r = p;
  35558. result.g = q;
  35559. result.b = v;
  35560. break;
  35561. case 4:
  35562. result.r = t;
  35563. result.g = p;
  35564. result.b = v;
  35565. break;
  35566. default:// case 5:
  35567. result.r = v;
  35568. result.g = p;
  35569. result.b = q;
  35570. break;
  35571. }
  35572. }
  35573. result.a = 1;
  35574. };
  35575. /**
  35576. * Returns a value clamped between min and max
  35577. * @param value The value to clamp
  35578. * @param min The minimum of value
  35579. * @param max The maximum of value
  35580. * @returns The clamped value.
  35581. */
  35582. ColorCurves.clamp = function (value, min, max) {
  35583. return Math.min(Math.max(value, min), max);
  35584. };
  35585. /**
  35586. * Clones the current color curve instance.
  35587. * @return The cloned curves
  35588. */
  35589. ColorCurves.prototype.clone = function () {
  35590. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35591. };
  35592. /**
  35593. * Serializes the current color curve instance to a json representation.
  35594. * @return a JSON representation
  35595. */
  35596. ColorCurves.prototype.serialize = function () {
  35597. return BABYLON.SerializationHelper.Serialize(this);
  35598. };
  35599. /**
  35600. * Parses the color curve from a json representation.
  35601. * @param source the JSON source to parse
  35602. * @return The parsed curves
  35603. */
  35604. ColorCurves.Parse = function (source) {
  35605. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35606. };
  35607. __decorate([
  35608. BABYLON.serialize()
  35609. ], ColorCurves.prototype, "_globalHue", void 0);
  35610. __decorate([
  35611. BABYLON.serialize()
  35612. ], ColorCurves.prototype, "_globalDensity", void 0);
  35613. __decorate([
  35614. BABYLON.serialize()
  35615. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35616. __decorate([
  35617. BABYLON.serialize()
  35618. ], ColorCurves.prototype, "_globalExposure", void 0);
  35619. __decorate([
  35620. BABYLON.serialize()
  35621. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35622. __decorate([
  35623. BABYLON.serialize()
  35624. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35625. __decorate([
  35626. BABYLON.serialize()
  35627. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35628. __decorate([
  35629. BABYLON.serialize()
  35630. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35631. __decorate([
  35632. BABYLON.serialize()
  35633. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35634. __decorate([
  35635. BABYLON.serialize()
  35636. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35637. __decorate([
  35638. BABYLON.serialize()
  35639. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35640. __decorate([
  35641. BABYLON.serialize()
  35642. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  35643. return ColorCurves;
  35644. }());
  35645. BABYLON.ColorCurves = ColorCurves;
  35646. })(BABYLON || (BABYLON = {}));
  35647. //# sourceMappingURL=babylon.colorCurves.js.map
  35648. //# sourceMappingURL=babylon.behavior.js.map
  35649. var BABYLON;
  35650. (function (BABYLON) {
  35651. var MaterialHelper = /** @class */ (function () {
  35652. function MaterialHelper() {
  35653. }
  35654. MaterialHelper.BindEyePosition = function (effect, scene) {
  35655. if (scene._forcedViewPosition) {
  35656. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35657. return;
  35658. }
  35659. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35660. };
  35661. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  35662. defines._needUVs = true;
  35663. defines[key] = true;
  35664. if (texture.getTextureMatrix().isIdentity(true)) {
  35665. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  35666. if (texture.coordinatesIndex === 0) {
  35667. defines["MAINUV1"] = true;
  35668. }
  35669. else {
  35670. defines["MAINUV2"] = true;
  35671. }
  35672. }
  35673. else {
  35674. defines[key + "DIRECTUV"] = 0;
  35675. }
  35676. };
  35677. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  35678. var matrix = texture.getTextureMatrix();
  35679. if (!matrix.isIdentity(true)) {
  35680. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  35681. }
  35682. };
  35683. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  35684. if (defines._areMiscDirty) {
  35685. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  35686. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  35687. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  35688. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  35689. }
  35690. };
  35691. /**
  35692. * Helper used to prepare the list of defines for shader compilation
  35693. * @param scene defines the current scene
  35694. * @param engine defines the current engine
  35695. * @param defines specifies the list of active defines
  35696. * @param useInstances defines if instances have to be turned on
  35697. * @param alphaTest defines if alpha testing has to be turned on
  35698. */
  35699. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  35700. var changed = false;
  35701. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  35702. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  35703. changed = true;
  35704. }
  35705. if (defines["ALPHATEST"] !== alphaTest) {
  35706. defines["ALPHATEST"] = !defines["ALPHATEST"];
  35707. changed = true;
  35708. }
  35709. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  35710. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  35711. changed = true;
  35712. }
  35713. if (defines["INSTANCES"] !== useInstances) {
  35714. defines["INSTANCES"] = useInstances;
  35715. changed = true;
  35716. }
  35717. if (changed) {
  35718. defines.markAsUnprocessed();
  35719. }
  35720. };
  35721. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  35722. if (useMorphTargets === void 0) { useMorphTargets = false; }
  35723. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  35724. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  35725. return false;
  35726. }
  35727. defines._normals = defines._needNormals;
  35728. defines._uvs = defines._needUVs;
  35729. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  35730. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35731. defines["TANGENT"] = true;
  35732. }
  35733. if (defines._needUVs) {
  35734. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  35735. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  35736. }
  35737. else {
  35738. defines["UV1"] = false;
  35739. defines["UV2"] = false;
  35740. }
  35741. if (useVertexColor) {
  35742. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  35743. defines["VERTEXCOLOR"] = hasVertexColors;
  35744. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  35745. }
  35746. if (useBones) {
  35747. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35748. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  35749. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  35750. }
  35751. else {
  35752. defines["NUM_BONE_INFLUENCERS"] = 0;
  35753. defines["BonesPerMesh"] = 0;
  35754. }
  35755. }
  35756. if (useMorphTargets) {
  35757. var manager = mesh.morphTargetManager;
  35758. if (manager) {
  35759. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  35760. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  35761. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  35762. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  35763. }
  35764. else {
  35765. defines["MORPHTARGETS_TANGENT"] = false;
  35766. defines["MORPHTARGETS_NORMAL"] = false;
  35767. defines["MORPHTARGETS"] = false;
  35768. defines["NUM_MORPH_INFLUENCERS"] = 0;
  35769. }
  35770. }
  35771. return true;
  35772. };
  35773. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  35774. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35775. if (disableLighting === void 0) { disableLighting = false; }
  35776. if (!defines._areLightsDirty) {
  35777. return defines._needNormals;
  35778. }
  35779. var lightIndex = 0;
  35780. var needNormals = false;
  35781. var needRebuild = false;
  35782. var lightmapMode = false;
  35783. var shadowEnabled = false;
  35784. var specularEnabled = false;
  35785. if (scene.lightsEnabled && !disableLighting) {
  35786. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  35787. var light = _a[_i];
  35788. needNormals = true;
  35789. if (defines["LIGHT" + lightIndex] === undefined) {
  35790. needRebuild = true;
  35791. }
  35792. defines["LIGHT" + lightIndex] = true;
  35793. defines["SPOTLIGHT" + lightIndex] = false;
  35794. defines["HEMILIGHT" + lightIndex] = false;
  35795. defines["POINTLIGHT" + lightIndex] = false;
  35796. defines["DIRLIGHT" + lightIndex] = false;
  35797. var type;
  35798. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  35799. type = "SPOTLIGHT" + lightIndex;
  35800. }
  35801. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  35802. type = "HEMILIGHT" + lightIndex;
  35803. }
  35804. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  35805. type = "POINTLIGHT" + lightIndex;
  35806. }
  35807. else {
  35808. type = "DIRLIGHT" + lightIndex;
  35809. }
  35810. defines[type] = true;
  35811. // Specular
  35812. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  35813. specularEnabled = true;
  35814. }
  35815. // Shadows
  35816. defines["SHADOW" + lightIndex] = false;
  35817. defines["SHADOWPCF" + lightIndex] = false;
  35818. defines["SHADOWESM" + lightIndex] = false;
  35819. defines["SHADOWCUBE" + lightIndex] = false;
  35820. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  35821. var shadowGenerator = light.getShadowGenerator();
  35822. if (shadowGenerator) {
  35823. shadowEnabled = true;
  35824. shadowGenerator.prepareDefines(defines, lightIndex);
  35825. }
  35826. }
  35827. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  35828. lightmapMode = true;
  35829. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  35830. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  35831. }
  35832. else {
  35833. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  35834. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  35835. }
  35836. lightIndex++;
  35837. if (lightIndex === maxSimultaneousLights)
  35838. break;
  35839. }
  35840. }
  35841. defines["SPECULARTERM"] = specularEnabled;
  35842. defines["SHADOWS"] = shadowEnabled;
  35843. // Resetting all other lights if any
  35844. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  35845. if (defines["LIGHT" + index] !== undefined) {
  35846. defines["LIGHT" + index] = false;
  35847. defines["HEMILIGHT" + lightIndex] = false;
  35848. defines["POINTLIGHT" + lightIndex] = false;
  35849. defines["DIRLIGHT" + lightIndex] = false;
  35850. defines["SPOTLIGHT" + lightIndex] = false;
  35851. defines["SHADOW" + lightIndex] = false;
  35852. }
  35853. }
  35854. var caps = scene.getEngine().getCaps();
  35855. if (defines["SHADOWFLOAT"] === undefined) {
  35856. needRebuild = true;
  35857. }
  35858. defines["SHADOWFLOAT"] = shadowEnabled &&
  35859. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  35860. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  35861. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  35862. if (needRebuild) {
  35863. defines.rebuild();
  35864. }
  35865. return needNormals;
  35866. };
  35867. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  35868. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35869. var uniformsList;
  35870. var uniformBuffersList = null;
  35871. if (uniformsListOrOptions.uniformsNames) {
  35872. var options = uniformsListOrOptions;
  35873. uniformsList = options.uniformsNames;
  35874. uniformBuffersList = options.uniformBuffersNames;
  35875. samplersList = options.samplers;
  35876. defines = options.defines;
  35877. maxSimultaneousLights = options.maxSimultaneousLights;
  35878. }
  35879. else {
  35880. uniformsList = uniformsListOrOptions;
  35881. if (!samplersList) {
  35882. samplersList = [];
  35883. }
  35884. }
  35885. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35886. if (!defines["LIGHT" + lightIndex]) {
  35887. break;
  35888. }
  35889. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  35890. if (uniformBuffersList) {
  35891. uniformBuffersList.push("Light" + lightIndex);
  35892. }
  35893. samplersList.push("shadowSampler" + lightIndex);
  35894. }
  35895. if (defines["NUM_MORPH_INFLUENCERS"]) {
  35896. uniformsList.push("morphTargetInfluences");
  35897. }
  35898. };
  35899. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  35900. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35901. if (rank === void 0) { rank = 0; }
  35902. var lightFallbackRank = 0;
  35903. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35904. if (!defines["LIGHT" + lightIndex]) {
  35905. break;
  35906. }
  35907. if (lightIndex > 0) {
  35908. lightFallbackRank = rank + lightIndex;
  35909. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  35910. }
  35911. if (!defines["SHADOWS"]) {
  35912. if (defines["SHADOW" + lightIndex]) {
  35913. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  35914. }
  35915. if (defines["SHADOWPCF" + lightIndex]) {
  35916. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  35917. }
  35918. if (defines["SHADOWESM" + lightIndex]) {
  35919. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  35920. }
  35921. }
  35922. }
  35923. return lightFallbackRank++;
  35924. };
  35925. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  35926. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  35927. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  35928. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  35929. var manager = mesh.morphTargetManager;
  35930. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  35931. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  35932. for (var index = 0; index < influencers; index++) {
  35933. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  35934. if (normal) {
  35935. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  35936. }
  35937. if (tangent) {
  35938. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  35939. }
  35940. if (attribs.length > maxAttributesCount) {
  35941. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  35942. }
  35943. }
  35944. }
  35945. };
  35946. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  35947. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  35948. fallbacks.addCPUSkinningFallback(0, mesh);
  35949. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35950. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35951. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  35952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35954. }
  35955. }
  35956. };
  35957. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  35958. if (defines["INSTANCES"]) {
  35959. attribs.push("world0");
  35960. attribs.push("world1");
  35961. attribs.push("world2");
  35962. attribs.push("world3");
  35963. }
  35964. };
  35965. // Bindings
  35966. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  35967. if (light.shadowEnabled && mesh.receiveShadows) {
  35968. var shadowGenerator = light.getShadowGenerator();
  35969. if (shadowGenerator) {
  35970. shadowGenerator.bindShadowLight(lightIndex, effect);
  35971. }
  35972. }
  35973. };
  35974. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  35975. light.transferToEffect(effect, lightIndex + "");
  35976. };
  35977. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  35978. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35979. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  35980. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  35981. for (var i = 0; i < len; i++) {
  35982. var light = mesh._lightSources[i];
  35983. var iAsString = i.toString();
  35984. var scaledIntensity = light.getScaledIntensity();
  35985. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  35986. MaterialHelper.BindLightProperties(light, effect, i);
  35987. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  35988. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  35989. if (defines["SPECULARTERM"]) {
  35990. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  35991. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  35992. }
  35993. // Shadows
  35994. if (scene.shadowsEnabled) {
  35995. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  35996. }
  35997. light._uniformBuffer.update();
  35998. }
  35999. };
  36000. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36001. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36002. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36003. effect.setColor3("vFogColor", scene.fogColor);
  36004. }
  36005. };
  36006. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36007. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36008. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36009. if (matrices && effect) {
  36010. effect.setMatrices("mBones", matrices);
  36011. }
  36012. }
  36013. };
  36014. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36015. var manager = abstractMesh.morphTargetManager;
  36016. if (!abstractMesh || !manager) {
  36017. return;
  36018. }
  36019. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36020. };
  36021. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36022. if (defines["LOGARITHMICDEPTH"]) {
  36023. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36024. }
  36025. };
  36026. MaterialHelper.BindClipPlane = function (effect, scene) {
  36027. if (scene.clipPlane) {
  36028. var clipPlane = scene.clipPlane;
  36029. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36030. }
  36031. };
  36032. return MaterialHelper;
  36033. }());
  36034. BABYLON.MaterialHelper = MaterialHelper;
  36035. })(BABYLON || (BABYLON = {}));
  36036. //# sourceMappingURL=babylon.materialHelper.js.map
  36037. var BABYLON;
  36038. (function (BABYLON) {
  36039. var PushMaterial = /** @class */ (function (_super) {
  36040. __extends(PushMaterial, _super);
  36041. function PushMaterial(name, scene) {
  36042. var _this = _super.call(this, name, scene) || this;
  36043. _this.storeEffectOnSubMeshes = true;
  36044. return _this;
  36045. }
  36046. PushMaterial.prototype.getEffect = function () {
  36047. return this._activeEffect;
  36048. };
  36049. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36050. if (!mesh) {
  36051. return false;
  36052. }
  36053. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36054. return true;
  36055. }
  36056. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36057. };
  36058. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36059. this._activeEffect.setMatrix("world", world);
  36060. };
  36061. PushMaterial.prototype.bind = function (world, mesh) {
  36062. if (!mesh) {
  36063. return;
  36064. }
  36065. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36066. };
  36067. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36068. if (effect === void 0) { effect = null; }
  36069. _super.prototype._afterBind.call(this, mesh);
  36070. this.getScene()._cachedEffect = effect;
  36071. };
  36072. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36073. if (visibility === void 0) { visibility = 1; }
  36074. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36075. };
  36076. return PushMaterial;
  36077. }(BABYLON.Material));
  36078. BABYLON.PushMaterial = PushMaterial;
  36079. })(BABYLON || (BABYLON = {}));
  36080. //# sourceMappingURL=babylon.pushMaterial.js.map
  36081. var BABYLON;
  36082. (function (BABYLON) {
  36083. var StandardMaterialDefines = /** @class */ (function (_super) {
  36084. __extends(StandardMaterialDefines, _super);
  36085. function StandardMaterialDefines() {
  36086. var _this = _super.call(this) || this;
  36087. _this.MAINUV1 = false;
  36088. _this.MAINUV2 = false;
  36089. _this.DIFFUSE = false;
  36090. _this.DIFFUSEDIRECTUV = 0;
  36091. _this.AMBIENT = false;
  36092. _this.AMBIENTDIRECTUV = 0;
  36093. _this.OPACITY = false;
  36094. _this.OPACITYDIRECTUV = 0;
  36095. _this.OPACITYRGB = false;
  36096. _this.REFLECTION = false;
  36097. _this.EMISSIVE = false;
  36098. _this.EMISSIVEDIRECTUV = 0;
  36099. _this.SPECULAR = false;
  36100. _this.SPECULARDIRECTUV = 0;
  36101. _this.BUMP = false;
  36102. _this.BUMPDIRECTUV = 0;
  36103. _this.PARALLAX = false;
  36104. _this.PARALLAXOCCLUSION = false;
  36105. _this.SPECULAROVERALPHA = false;
  36106. _this.CLIPPLANE = false;
  36107. _this.ALPHATEST = false;
  36108. _this.DEPTHPREPASS = false;
  36109. _this.ALPHAFROMDIFFUSE = false;
  36110. _this.POINTSIZE = false;
  36111. _this.FOG = false;
  36112. _this.SPECULARTERM = false;
  36113. _this.DIFFUSEFRESNEL = false;
  36114. _this.OPACITYFRESNEL = false;
  36115. _this.REFLECTIONFRESNEL = false;
  36116. _this.REFRACTIONFRESNEL = false;
  36117. _this.EMISSIVEFRESNEL = false;
  36118. _this.FRESNEL = false;
  36119. _this.NORMAL = false;
  36120. _this.UV1 = false;
  36121. _this.UV2 = false;
  36122. _this.VERTEXCOLOR = false;
  36123. _this.VERTEXALPHA = false;
  36124. _this.NUM_BONE_INFLUENCERS = 0;
  36125. _this.BonesPerMesh = 0;
  36126. _this.INSTANCES = false;
  36127. _this.GLOSSINESS = false;
  36128. _this.ROUGHNESS = false;
  36129. _this.EMISSIVEASILLUMINATION = false;
  36130. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36131. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36132. _this.LIGHTMAP = false;
  36133. _this.LIGHTMAPDIRECTUV = 0;
  36134. _this.USELIGHTMAPASSHADOWMAP = false;
  36135. _this.REFLECTIONMAP_3D = false;
  36136. _this.REFLECTIONMAP_SPHERICAL = false;
  36137. _this.REFLECTIONMAP_PLANAR = false;
  36138. _this.REFLECTIONMAP_CUBIC = false;
  36139. _this.REFLECTIONMAP_PROJECTION = false;
  36140. _this.REFLECTIONMAP_SKYBOX = false;
  36141. _this.REFLECTIONMAP_EXPLICIT = false;
  36142. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36143. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36144. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36145. _this.INVERTCUBICMAP = false;
  36146. _this.LOGARITHMICDEPTH = false;
  36147. _this.REFRACTION = false;
  36148. _this.REFRACTIONMAP_3D = false;
  36149. _this.REFLECTIONOVERALPHA = false;
  36150. _this.TWOSIDEDLIGHTING = false;
  36151. _this.SHADOWFLOAT = false;
  36152. _this.MORPHTARGETS = false;
  36153. _this.MORPHTARGETS_NORMAL = false;
  36154. _this.MORPHTARGETS_TANGENT = false;
  36155. _this.NUM_MORPH_INFLUENCERS = 0;
  36156. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36157. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36158. _this.IMAGEPROCESSING = false;
  36159. _this.VIGNETTE = false;
  36160. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36161. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36162. _this.TONEMAPPING = false;
  36163. _this.CONTRAST = false;
  36164. _this.COLORCURVES = false;
  36165. _this.COLORGRADING = false;
  36166. _this.COLORGRADING3D = false;
  36167. _this.SAMPLER3DGREENDEPTH = false;
  36168. _this.SAMPLER3DBGRMAP = false;
  36169. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36170. _this.EXPOSURE = false;
  36171. _this.rebuild();
  36172. return _this;
  36173. }
  36174. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36175. var modes = [
  36176. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36177. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36178. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36179. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36180. ];
  36181. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36182. var mode = modes_1[_i];
  36183. this[mode] = (mode === modeToEnable);
  36184. }
  36185. };
  36186. return StandardMaterialDefines;
  36187. }(BABYLON.MaterialDefines));
  36188. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36189. var StandardMaterial = /** @class */ (function (_super) {
  36190. __extends(StandardMaterial, _super);
  36191. function StandardMaterial(name, scene) {
  36192. var _this = _super.call(this, name, scene) || this;
  36193. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36194. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36195. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36196. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36197. _this.specularPower = 64;
  36198. _this._useAlphaFromDiffuseTexture = false;
  36199. _this._useEmissiveAsIllumination = false;
  36200. _this._linkEmissiveWithDiffuse = false;
  36201. _this._useSpecularOverAlpha = false;
  36202. _this._useReflectionOverAlpha = false;
  36203. _this._disableLighting = false;
  36204. _this._useParallax = false;
  36205. _this._useParallaxOcclusion = false;
  36206. _this.parallaxScaleBias = 0.05;
  36207. _this._roughness = 0;
  36208. _this.indexOfRefraction = 0.98;
  36209. _this.invertRefractionY = true;
  36210. _this._useLightmapAsShadowmap = false;
  36211. _this._useReflectionFresnelFromSpecular = false;
  36212. _this._useGlossinessFromSpecularMapAlpha = false;
  36213. _this._maxSimultaneousLights = 4;
  36214. /**
  36215. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36216. */
  36217. _this._invertNormalMapX = false;
  36218. /**
  36219. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36220. */
  36221. _this._invertNormalMapY = false;
  36222. /**
  36223. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36224. */
  36225. _this._twoSidedLighting = false;
  36226. _this._renderTargets = new BABYLON.SmartArray(16);
  36227. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36228. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36229. // Setup the default processing configuration to the scene.
  36230. _this._attachImageProcessingConfiguration(null);
  36231. _this.getRenderTargetTextures = function () {
  36232. _this._renderTargets.reset();
  36233. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36234. _this._renderTargets.push(_this._reflectionTexture);
  36235. }
  36236. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36237. _this._renderTargets.push(_this._refractionTexture);
  36238. }
  36239. return _this._renderTargets;
  36240. };
  36241. return _this;
  36242. }
  36243. ;
  36244. ;
  36245. ;
  36246. ;
  36247. ;
  36248. ;
  36249. ;
  36250. ;
  36251. ;
  36252. ;
  36253. ;
  36254. ;
  36255. ;
  36256. ;
  36257. ;
  36258. ;
  36259. ;
  36260. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36261. /**
  36262. * Gets the image processing configuration used either in this material.
  36263. */
  36264. get: function () {
  36265. return this._imageProcessingConfiguration;
  36266. },
  36267. /**
  36268. * Sets the Default image processing configuration used either in the this material.
  36269. *
  36270. * If sets to null, the scene one is in use.
  36271. */
  36272. set: function (value) {
  36273. this._attachImageProcessingConfiguration(value);
  36274. // Ensure the effect will be rebuilt.
  36275. this._markAllSubMeshesAsTexturesDirty();
  36276. },
  36277. enumerable: true,
  36278. configurable: true
  36279. });
  36280. /**
  36281. * Attaches a new image processing configuration to the Standard Material.
  36282. * @param configuration
  36283. */
  36284. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36285. var _this = this;
  36286. if (configuration === this._imageProcessingConfiguration) {
  36287. return;
  36288. }
  36289. // Detaches observer.
  36290. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36291. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36292. }
  36293. // Pick the scene configuration if needed.
  36294. if (!configuration) {
  36295. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36296. }
  36297. else {
  36298. this._imageProcessingConfiguration = configuration;
  36299. }
  36300. // Attaches observer.
  36301. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36302. _this._markAllSubMeshesAsImageProcessingDirty();
  36303. });
  36304. };
  36305. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36306. /**
  36307. * Gets wether the color curves effect is enabled.
  36308. */
  36309. get: function () {
  36310. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36311. },
  36312. /**
  36313. * Sets wether the color curves effect is enabled.
  36314. */
  36315. set: function (value) {
  36316. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36317. },
  36318. enumerable: true,
  36319. configurable: true
  36320. });
  36321. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36322. /**
  36323. * Gets wether the color grading effect is enabled.
  36324. */
  36325. get: function () {
  36326. return this.imageProcessingConfiguration.colorGradingEnabled;
  36327. },
  36328. /**
  36329. * Gets wether the color grading effect is enabled.
  36330. */
  36331. set: function (value) {
  36332. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36333. },
  36334. enumerable: true,
  36335. configurable: true
  36336. });
  36337. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36338. /**
  36339. * Gets wether tonemapping is enabled or not.
  36340. */
  36341. get: function () {
  36342. return this._imageProcessingConfiguration.toneMappingEnabled;
  36343. },
  36344. /**
  36345. * Sets wether tonemapping is enabled or not
  36346. */
  36347. set: function (value) {
  36348. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36349. },
  36350. enumerable: true,
  36351. configurable: true
  36352. });
  36353. ;
  36354. ;
  36355. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36356. /**
  36357. * The camera exposure used on this material.
  36358. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36359. * This corresponds to a photographic exposure.
  36360. */
  36361. get: function () {
  36362. return this._imageProcessingConfiguration.exposure;
  36363. },
  36364. /**
  36365. * The camera exposure used on this material.
  36366. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36367. * This corresponds to a photographic exposure.
  36368. */
  36369. set: function (value) {
  36370. this._imageProcessingConfiguration.exposure = value;
  36371. },
  36372. enumerable: true,
  36373. configurable: true
  36374. });
  36375. ;
  36376. ;
  36377. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36378. /**
  36379. * Gets The camera contrast used on this material.
  36380. */
  36381. get: function () {
  36382. return this._imageProcessingConfiguration.contrast;
  36383. },
  36384. /**
  36385. * Sets The camera contrast used on this material.
  36386. */
  36387. set: function (value) {
  36388. this._imageProcessingConfiguration.contrast = value;
  36389. },
  36390. enumerable: true,
  36391. configurable: true
  36392. });
  36393. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36394. /**
  36395. * Gets the Color Grading 2D Lookup Texture.
  36396. */
  36397. get: function () {
  36398. return this._imageProcessingConfiguration.colorGradingTexture;
  36399. },
  36400. /**
  36401. * Sets the Color Grading 2D Lookup Texture.
  36402. */
  36403. set: function (value) {
  36404. this._imageProcessingConfiguration.colorGradingTexture = value;
  36405. },
  36406. enumerable: true,
  36407. configurable: true
  36408. });
  36409. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36410. /**
  36411. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36412. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36413. * 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;
  36414. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36415. */
  36416. get: function () {
  36417. return this._imageProcessingConfiguration.colorCurves;
  36418. },
  36419. /**
  36420. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36421. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36422. * 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;
  36423. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36424. */
  36425. set: function (value) {
  36426. this._imageProcessingConfiguration.colorCurves = value;
  36427. },
  36428. enumerable: true,
  36429. configurable: true
  36430. });
  36431. StandardMaterial.prototype.getClassName = function () {
  36432. return "StandardMaterial";
  36433. };
  36434. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36435. get: function () {
  36436. return this._useLogarithmicDepth;
  36437. },
  36438. set: function (value) {
  36439. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36440. this._markAllSubMeshesAsMiscDirty();
  36441. },
  36442. enumerable: true,
  36443. configurable: true
  36444. });
  36445. StandardMaterial.prototype.needAlphaBlending = function () {
  36446. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36447. };
  36448. StandardMaterial.prototype.needAlphaTesting = function () {
  36449. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36450. };
  36451. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36452. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36453. };
  36454. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36455. return this._diffuseTexture;
  36456. };
  36457. /**
  36458. * Child classes can use it to update shaders
  36459. */
  36460. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36461. if (useInstances === void 0) { useInstances = false; }
  36462. if (subMesh.effect && this.isFrozen) {
  36463. if (this._wasPreviouslyReady && subMesh.effect) {
  36464. return true;
  36465. }
  36466. }
  36467. if (!subMesh._materialDefines) {
  36468. subMesh._materialDefines = new StandardMaterialDefines();
  36469. }
  36470. var scene = this.getScene();
  36471. var defines = subMesh._materialDefines;
  36472. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36473. if (defines._renderId === scene.getRenderId()) {
  36474. return true;
  36475. }
  36476. }
  36477. var engine = scene.getEngine();
  36478. // Lights
  36479. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36480. // Textures
  36481. if (defines._areTexturesDirty) {
  36482. defines._needUVs = false;
  36483. defines.MAINUV1 = false;
  36484. defines.MAINUV2 = false;
  36485. if (scene.texturesEnabled) {
  36486. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36487. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36488. return false;
  36489. }
  36490. else {
  36491. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36492. }
  36493. }
  36494. else {
  36495. defines.DIFFUSE = false;
  36496. }
  36497. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36498. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36499. return false;
  36500. }
  36501. else {
  36502. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36503. }
  36504. }
  36505. else {
  36506. defines.AMBIENT = false;
  36507. }
  36508. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36509. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36510. return false;
  36511. }
  36512. else {
  36513. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36514. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36515. }
  36516. }
  36517. else {
  36518. defines.OPACITY = false;
  36519. }
  36520. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36521. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36522. return false;
  36523. }
  36524. else {
  36525. defines._needNormals = true;
  36526. defines.REFLECTION = true;
  36527. defines.ROUGHNESS = (this._roughness > 0);
  36528. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36529. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36530. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36531. switch (this._reflectionTexture.coordinatesMode) {
  36532. case BABYLON.Texture.CUBIC_MODE:
  36533. case BABYLON.Texture.INVCUBIC_MODE:
  36534. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36535. break;
  36536. case BABYLON.Texture.EXPLICIT_MODE:
  36537. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36538. break;
  36539. case BABYLON.Texture.PLANAR_MODE:
  36540. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36541. break;
  36542. case BABYLON.Texture.PROJECTION_MODE:
  36543. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36544. break;
  36545. case BABYLON.Texture.SKYBOX_MODE:
  36546. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36547. break;
  36548. case BABYLON.Texture.SPHERICAL_MODE:
  36549. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36550. break;
  36551. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36552. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36553. break;
  36554. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36555. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36556. break;
  36557. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36558. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36559. break;
  36560. }
  36561. }
  36562. }
  36563. else {
  36564. defines.REFLECTION = false;
  36565. }
  36566. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36567. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36568. return false;
  36569. }
  36570. else {
  36571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36572. }
  36573. }
  36574. else {
  36575. defines.EMISSIVE = false;
  36576. }
  36577. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36578. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36579. return false;
  36580. }
  36581. else {
  36582. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36583. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36584. }
  36585. }
  36586. else {
  36587. defines.LIGHTMAP = false;
  36588. }
  36589. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36590. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36591. return false;
  36592. }
  36593. else {
  36594. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36595. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36596. }
  36597. }
  36598. else {
  36599. defines.SPECULAR = false;
  36600. }
  36601. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36602. // Bump texure can not be not blocking.
  36603. if (!this._bumpTexture.isReady()) {
  36604. return false;
  36605. }
  36606. else {
  36607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36608. defines.PARALLAX = this._useParallax;
  36609. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36610. }
  36611. }
  36612. else {
  36613. defines.BUMP = false;
  36614. }
  36615. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36616. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36617. return false;
  36618. }
  36619. else {
  36620. defines._needUVs = true;
  36621. defines.REFRACTION = true;
  36622. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36623. }
  36624. }
  36625. else {
  36626. defines.REFRACTION = false;
  36627. }
  36628. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36629. }
  36630. else {
  36631. defines.DIFFUSE = false;
  36632. defines.AMBIENT = false;
  36633. defines.OPACITY = false;
  36634. defines.REFLECTION = false;
  36635. defines.EMISSIVE = false;
  36636. defines.LIGHTMAP = false;
  36637. defines.BUMP = false;
  36638. defines.REFRACTION = false;
  36639. }
  36640. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  36641. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  36642. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  36643. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36644. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36645. }
  36646. if (defines._areImageProcessingDirty) {
  36647. if (!this._imageProcessingConfiguration.isReady()) {
  36648. return false;
  36649. }
  36650. this._imageProcessingConfiguration.prepareDefines(defines);
  36651. }
  36652. if (defines._areFresnelDirty) {
  36653. if (StandardMaterial.FresnelEnabled) {
  36654. // Fresnel
  36655. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  36656. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  36657. this._reflectionFresnelParameters) {
  36658. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  36659. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  36660. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  36661. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  36662. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  36663. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  36664. defines._needNormals = true;
  36665. defines.FRESNEL = true;
  36666. }
  36667. }
  36668. else {
  36669. defines.FRESNEL = false;
  36670. }
  36671. }
  36672. // Misc.
  36673. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36674. // Attribs
  36675. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  36676. // Values that need to be evaluated on every frame
  36677. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  36678. // Get correct effect
  36679. if (defines.isDirty) {
  36680. defines.markAsProcessed();
  36681. scene.resetCachedMaterial();
  36682. // Fallbacks
  36683. var fallbacks = new BABYLON.EffectFallbacks();
  36684. if (defines.REFLECTION) {
  36685. fallbacks.addFallback(0, "REFLECTION");
  36686. }
  36687. if (defines.SPECULAR) {
  36688. fallbacks.addFallback(0, "SPECULAR");
  36689. }
  36690. if (defines.BUMP) {
  36691. fallbacks.addFallback(0, "BUMP");
  36692. }
  36693. if (defines.PARALLAX) {
  36694. fallbacks.addFallback(1, "PARALLAX");
  36695. }
  36696. if (defines.PARALLAXOCCLUSION) {
  36697. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  36698. }
  36699. if (defines.SPECULAROVERALPHA) {
  36700. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  36701. }
  36702. if (defines.FOG) {
  36703. fallbacks.addFallback(1, "FOG");
  36704. }
  36705. if (defines.POINTSIZE) {
  36706. fallbacks.addFallback(0, "POINTSIZE");
  36707. }
  36708. if (defines.LOGARITHMICDEPTH) {
  36709. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  36710. }
  36711. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  36712. if (defines.SPECULARTERM) {
  36713. fallbacks.addFallback(0, "SPECULARTERM");
  36714. }
  36715. if (defines.DIFFUSEFRESNEL) {
  36716. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  36717. }
  36718. if (defines.OPACITYFRESNEL) {
  36719. fallbacks.addFallback(2, "OPACITYFRESNEL");
  36720. }
  36721. if (defines.REFLECTIONFRESNEL) {
  36722. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  36723. }
  36724. if (defines.EMISSIVEFRESNEL) {
  36725. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  36726. }
  36727. if (defines.FRESNEL) {
  36728. fallbacks.addFallback(4, "FRESNEL");
  36729. }
  36730. //Attributes
  36731. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36732. if (defines.NORMAL) {
  36733. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36734. }
  36735. if (defines.UV1) {
  36736. attribs.push(BABYLON.VertexBuffer.UVKind);
  36737. }
  36738. if (defines.UV2) {
  36739. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36740. }
  36741. if (defines.VERTEXCOLOR) {
  36742. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36743. }
  36744. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36745. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36746. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36747. var shaderName = "default";
  36748. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  36749. "vFogInfos", "vFogColor", "pointSize",
  36750. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36751. "mBones",
  36752. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36753. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  36754. "logarithmicDepthConstant", "vTangentSpaceParams"
  36755. ];
  36756. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  36757. var uniformBuffers = ["Material", "Scene"];
  36758. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36759. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36760. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36761. uniformsNames: uniforms,
  36762. uniformBuffersNames: uniformBuffers,
  36763. samplers: samplers,
  36764. defines: defines,
  36765. maxSimultaneousLights: this._maxSimultaneousLights
  36766. });
  36767. if (this.customShaderNameResolve) {
  36768. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  36769. }
  36770. var join = defines.toString();
  36771. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  36772. attributes: attribs,
  36773. uniformsNames: uniforms,
  36774. uniformBuffersNames: uniformBuffers,
  36775. samplers: samplers,
  36776. defines: join,
  36777. fallbacks: fallbacks,
  36778. onCompiled: this.onCompiled,
  36779. onError: this.onError,
  36780. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36781. }, engine), defines);
  36782. this.buildUniformLayout();
  36783. }
  36784. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36785. return false;
  36786. }
  36787. defines._renderId = scene.getRenderId();
  36788. this._wasPreviouslyReady = true;
  36789. return true;
  36790. };
  36791. StandardMaterial.prototype.buildUniformLayout = function () {
  36792. // Order is important !
  36793. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  36794. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  36795. this._uniformBuffer.addUniform("opacityParts", 4);
  36796. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  36797. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  36798. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  36799. this._uniformBuffer.addUniform("refractionRightColor", 4);
  36800. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  36801. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  36802. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  36803. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  36804. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36805. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36806. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36807. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36808. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  36809. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36810. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  36811. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36812. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36813. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36814. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36815. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36816. this._uniformBuffer.addUniform("specularMatrix", 16);
  36817. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36818. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36819. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36820. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36821. this._uniformBuffer.addUniform("vSpecularColor", 4);
  36822. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36823. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  36824. this._uniformBuffer.addUniform("pointSize", 1);
  36825. this._uniformBuffer.create();
  36826. };
  36827. StandardMaterial.prototype.unbind = function () {
  36828. if (this._activeEffect) {
  36829. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36830. this._activeEffect.setTexture("reflection2DSampler", null);
  36831. }
  36832. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36833. this._activeEffect.setTexture("refraction2DSampler", null);
  36834. }
  36835. }
  36836. _super.prototype.unbind.call(this);
  36837. };
  36838. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36839. var scene = this.getScene();
  36840. var defines = subMesh._materialDefines;
  36841. if (!defines) {
  36842. return;
  36843. }
  36844. var effect = subMesh.effect;
  36845. if (!effect) {
  36846. return;
  36847. }
  36848. this._activeEffect = effect;
  36849. // Matrices
  36850. this.bindOnlyWorldMatrix(world);
  36851. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36852. // Bones
  36853. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  36854. if (mustRebind) {
  36855. this._uniformBuffer.bindToEffect(effect, "Material");
  36856. this.bindViewProjection(effect);
  36857. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36858. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  36859. // Fresnel
  36860. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  36861. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  36862. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  36863. }
  36864. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  36865. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  36866. }
  36867. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  36868. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  36869. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  36870. }
  36871. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  36872. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  36873. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  36874. }
  36875. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  36876. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  36877. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  36878. }
  36879. }
  36880. // Textures
  36881. if (scene.texturesEnabled) {
  36882. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36883. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  36884. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  36885. }
  36886. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36887. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  36888. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36889. }
  36890. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36891. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36892. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36893. }
  36894. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36895. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  36896. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  36897. }
  36898. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36899. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36900. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36901. }
  36902. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36903. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36904. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36905. }
  36906. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36907. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  36908. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  36909. }
  36910. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36911. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  36912. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36913. if (scene._mirroredCameraPosition) {
  36914. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36915. }
  36916. else {
  36917. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36918. }
  36919. }
  36920. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36921. var depth = 1.0;
  36922. if (!this._refractionTexture.isCube) {
  36923. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  36924. if (this._refractionTexture.depth) {
  36925. depth = this._refractionTexture.depth;
  36926. }
  36927. }
  36928. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  36929. }
  36930. }
  36931. // Point size
  36932. if (this.pointsCloud) {
  36933. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36934. }
  36935. if (defines.SPECULARTERM) {
  36936. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  36937. }
  36938. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  36939. // Diffuse
  36940. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  36941. }
  36942. // Textures
  36943. if (scene.texturesEnabled) {
  36944. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36945. effect.setTexture("diffuseSampler", this._diffuseTexture);
  36946. }
  36947. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36948. effect.setTexture("ambientSampler", this._ambientTexture);
  36949. }
  36950. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36951. effect.setTexture("opacitySampler", this._opacityTexture);
  36952. }
  36953. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36954. if (this._reflectionTexture.isCube) {
  36955. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  36956. }
  36957. else {
  36958. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  36959. }
  36960. }
  36961. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36962. effect.setTexture("emissiveSampler", this._emissiveTexture);
  36963. }
  36964. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36965. effect.setTexture("lightmapSampler", this._lightmapTexture);
  36966. }
  36967. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36968. effect.setTexture("specularSampler", this._specularTexture);
  36969. }
  36970. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36971. effect.setTexture("bumpSampler", this._bumpTexture);
  36972. }
  36973. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36974. var depth = 1.0;
  36975. if (this._refractionTexture.isCube) {
  36976. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  36977. }
  36978. else {
  36979. effect.setTexture("refraction2DSampler", this._refractionTexture);
  36980. }
  36981. }
  36982. }
  36983. // Clip plane
  36984. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  36985. // Colors
  36986. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  36987. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  36988. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36989. }
  36990. if (mustRebind || !this.isFrozen) {
  36991. // Lights
  36992. if (scene.lightsEnabled && !this._disableLighting) {
  36993. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  36994. }
  36995. // View
  36996. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  36997. this.bindView(effect);
  36998. }
  36999. // Fog
  37000. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37001. // Morph targets
  37002. if (defines.NUM_MORPH_INFLUENCERS) {
  37003. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37004. }
  37005. // Log. depth
  37006. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37007. // image processing
  37008. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37009. this._imageProcessingConfiguration.bind(this._activeEffect);
  37010. }
  37011. }
  37012. this._uniformBuffer.update();
  37013. this._afterBind(mesh, this._activeEffect);
  37014. };
  37015. StandardMaterial.prototype.getAnimatables = function () {
  37016. var results = [];
  37017. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37018. results.push(this._diffuseTexture);
  37019. }
  37020. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37021. results.push(this._ambientTexture);
  37022. }
  37023. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37024. results.push(this._opacityTexture);
  37025. }
  37026. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37027. results.push(this._reflectionTexture);
  37028. }
  37029. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37030. results.push(this._emissiveTexture);
  37031. }
  37032. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37033. results.push(this._specularTexture);
  37034. }
  37035. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37036. results.push(this._bumpTexture);
  37037. }
  37038. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37039. results.push(this._lightmapTexture);
  37040. }
  37041. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37042. results.push(this._refractionTexture);
  37043. }
  37044. return results;
  37045. };
  37046. StandardMaterial.prototype.getActiveTextures = function () {
  37047. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37048. if (this._diffuseTexture) {
  37049. activeTextures.push(this._diffuseTexture);
  37050. }
  37051. if (this._ambientTexture) {
  37052. activeTextures.push(this._ambientTexture);
  37053. }
  37054. if (this._opacityTexture) {
  37055. activeTextures.push(this._opacityTexture);
  37056. }
  37057. if (this._reflectionTexture) {
  37058. activeTextures.push(this._reflectionTexture);
  37059. }
  37060. if (this._emissiveTexture) {
  37061. activeTextures.push(this._emissiveTexture);
  37062. }
  37063. if (this._specularTexture) {
  37064. activeTextures.push(this._specularTexture);
  37065. }
  37066. if (this._bumpTexture) {
  37067. activeTextures.push(this._bumpTexture);
  37068. }
  37069. if (this._lightmapTexture) {
  37070. activeTextures.push(this._lightmapTexture);
  37071. }
  37072. if (this._refractionTexture) {
  37073. activeTextures.push(this._refractionTexture);
  37074. }
  37075. return activeTextures;
  37076. };
  37077. StandardMaterial.prototype.hasTexture = function (texture) {
  37078. if (_super.prototype.hasTexture.call(this, texture)) {
  37079. return true;
  37080. }
  37081. if (this._diffuseTexture === texture) {
  37082. return true;
  37083. }
  37084. if (this._ambientTexture === texture) {
  37085. return true;
  37086. }
  37087. if (this._opacityTexture === texture) {
  37088. return true;
  37089. }
  37090. if (this._reflectionTexture === texture) {
  37091. return true;
  37092. }
  37093. if (this._emissiveTexture === texture) {
  37094. return true;
  37095. }
  37096. if (this._specularTexture === texture) {
  37097. return true;
  37098. }
  37099. if (this._bumpTexture === texture) {
  37100. return true;
  37101. }
  37102. if (this._lightmapTexture === texture) {
  37103. return true;
  37104. }
  37105. if (this._refractionTexture === texture) {
  37106. return true;
  37107. }
  37108. return false;
  37109. };
  37110. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37111. if (forceDisposeTextures) {
  37112. if (this._diffuseTexture) {
  37113. this._diffuseTexture.dispose();
  37114. }
  37115. if (this._ambientTexture) {
  37116. this._ambientTexture.dispose();
  37117. }
  37118. if (this._opacityTexture) {
  37119. this._opacityTexture.dispose();
  37120. }
  37121. if (this._reflectionTexture) {
  37122. this._reflectionTexture.dispose();
  37123. }
  37124. if (this._emissiveTexture) {
  37125. this._emissiveTexture.dispose();
  37126. }
  37127. if (this._specularTexture) {
  37128. this._specularTexture.dispose();
  37129. }
  37130. if (this._bumpTexture) {
  37131. this._bumpTexture.dispose();
  37132. }
  37133. if (this._lightmapTexture) {
  37134. this._lightmapTexture.dispose();
  37135. }
  37136. if (this._refractionTexture) {
  37137. this._refractionTexture.dispose();
  37138. }
  37139. }
  37140. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37141. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37142. }
  37143. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37144. };
  37145. StandardMaterial.prototype.clone = function (name) {
  37146. var _this = this;
  37147. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37148. result.name = name;
  37149. result.id = name;
  37150. return result;
  37151. };
  37152. StandardMaterial.prototype.serialize = function () {
  37153. return BABYLON.SerializationHelper.Serialize(this);
  37154. };
  37155. // Statics
  37156. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37157. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37158. };
  37159. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37160. get: function () {
  37161. return StandardMaterial._DiffuseTextureEnabled;
  37162. },
  37163. set: function (value) {
  37164. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37165. return;
  37166. }
  37167. StandardMaterial._DiffuseTextureEnabled = value;
  37168. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37169. },
  37170. enumerable: true,
  37171. configurable: true
  37172. });
  37173. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37174. get: function () {
  37175. return StandardMaterial._AmbientTextureEnabled;
  37176. },
  37177. set: function (value) {
  37178. if (StandardMaterial._AmbientTextureEnabled === value) {
  37179. return;
  37180. }
  37181. StandardMaterial._AmbientTextureEnabled = value;
  37182. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37183. },
  37184. enumerable: true,
  37185. configurable: true
  37186. });
  37187. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37188. get: function () {
  37189. return StandardMaterial._OpacityTextureEnabled;
  37190. },
  37191. set: function (value) {
  37192. if (StandardMaterial._OpacityTextureEnabled === value) {
  37193. return;
  37194. }
  37195. StandardMaterial._OpacityTextureEnabled = value;
  37196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37197. },
  37198. enumerable: true,
  37199. configurable: true
  37200. });
  37201. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37202. get: function () {
  37203. return StandardMaterial._ReflectionTextureEnabled;
  37204. },
  37205. set: function (value) {
  37206. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37207. return;
  37208. }
  37209. StandardMaterial._ReflectionTextureEnabled = value;
  37210. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37211. },
  37212. enumerable: true,
  37213. configurable: true
  37214. });
  37215. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37216. get: function () {
  37217. return StandardMaterial._EmissiveTextureEnabled;
  37218. },
  37219. set: function (value) {
  37220. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37221. return;
  37222. }
  37223. StandardMaterial._EmissiveTextureEnabled = value;
  37224. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37225. },
  37226. enumerable: true,
  37227. configurable: true
  37228. });
  37229. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37230. get: function () {
  37231. return StandardMaterial._SpecularTextureEnabled;
  37232. },
  37233. set: function (value) {
  37234. if (StandardMaterial._SpecularTextureEnabled === value) {
  37235. return;
  37236. }
  37237. StandardMaterial._SpecularTextureEnabled = value;
  37238. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37239. },
  37240. enumerable: true,
  37241. configurable: true
  37242. });
  37243. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37244. get: function () {
  37245. return StandardMaterial._BumpTextureEnabled;
  37246. },
  37247. set: function (value) {
  37248. if (StandardMaterial._BumpTextureEnabled === value) {
  37249. return;
  37250. }
  37251. StandardMaterial._BumpTextureEnabled = value;
  37252. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37253. },
  37254. enumerable: true,
  37255. configurable: true
  37256. });
  37257. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37258. get: function () {
  37259. return StandardMaterial._LightmapTextureEnabled;
  37260. },
  37261. set: function (value) {
  37262. if (StandardMaterial._LightmapTextureEnabled === value) {
  37263. return;
  37264. }
  37265. StandardMaterial._LightmapTextureEnabled = value;
  37266. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37267. },
  37268. enumerable: true,
  37269. configurable: true
  37270. });
  37271. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37272. get: function () {
  37273. return StandardMaterial._RefractionTextureEnabled;
  37274. },
  37275. set: function (value) {
  37276. if (StandardMaterial._RefractionTextureEnabled === value) {
  37277. return;
  37278. }
  37279. StandardMaterial._RefractionTextureEnabled = value;
  37280. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37281. },
  37282. enumerable: true,
  37283. configurable: true
  37284. });
  37285. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37286. get: function () {
  37287. return StandardMaterial._ColorGradingTextureEnabled;
  37288. },
  37289. set: function (value) {
  37290. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37291. return;
  37292. }
  37293. StandardMaterial._ColorGradingTextureEnabled = value;
  37294. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37295. },
  37296. enumerable: true,
  37297. configurable: true
  37298. });
  37299. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37300. get: function () {
  37301. return StandardMaterial._FresnelEnabled;
  37302. },
  37303. set: function (value) {
  37304. if (StandardMaterial._FresnelEnabled === value) {
  37305. return;
  37306. }
  37307. StandardMaterial._FresnelEnabled = value;
  37308. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37309. },
  37310. enumerable: true,
  37311. configurable: true
  37312. });
  37313. // Flags used to enable or disable a type of texture for all Standard Materials
  37314. StandardMaterial._DiffuseTextureEnabled = true;
  37315. StandardMaterial._AmbientTextureEnabled = true;
  37316. StandardMaterial._OpacityTextureEnabled = true;
  37317. StandardMaterial._ReflectionTextureEnabled = true;
  37318. StandardMaterial._EmissiveTextureEnabled = true;
  37319. StandardMaterial._SpecularTextureEnabled = true;
  37320. StandardMaterial._BumpTextureEnabled = true;
  37321. StandardMaterial._LightmapTextureEnabled = true;
  37322. StandardMaterial._RefractionTextureEnabled = true;
  37323. StandardMaterial._ColorGradingTextureEnabled = true;
  37324. StandardMaterial._FresnelEnabled = true;
  37325. __decorate([
  37326. BABYLON.serializeAsTexture("diffuseTexture")
  37327. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37328. __decorate([
  37329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37330. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37331. __decorate([
  37332. BABYLON.serializeAsTexture("ambientTexture")
  37333. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37334. __decorate([
  37335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37336. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37337. __decorate([
  37338. BABYLON.serializeAsTexture("opacityTexture")
  37339. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37340. __decorate([
  37341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37342. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37343. __decorate([
  37344. BABYLON.serializeAsTexture("reflectionTexture")
  37345. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37346. __decorate([
  37347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37348. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37349. __decorate([
  37350. BABYLON.serializeAsTexture("emissiveTexture")
  37351. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37352. __decorate([
  37353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37354. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37355. __decorate([
  37356. BABYLON.serializeAsTexture("specularTexture")
  37357. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37358. __decorate([
  37359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37360. ], StandardMaterial.prototype, "specularTexture", void 0);
  37361. __decorate([
  37362. BABYLON.serializeAsTexture("bumpTexture")
  37363. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37364. __decorate([
  37365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37366. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37367. __decorate([
  37368. BABYLON.serializeAsTexture("lightmapTexture")
  37369. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37370. __decorate([
  37371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37372. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37373. __decorate([
  37374. BABYLON.serializeAsTexture("refractionTexture")
  37375. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37376. __decorate([
  37377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37378. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37379. __decorate([
  37380. BABYLON.serializeAsColor3("ambient")
  37381. ], StandardMaterial.prototype, "ambientColor", void 0);
  37382. __decorate([
  37383. BABYLON.serializeAsColor3("diffuse")
  37384. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37385. __decorate([
  37386. BABYLON.serializeAsColor3("specular")
  37387. ], StandardMaterial.prototype, "specularColor", void 0);
  37388. __decorate([
  37389. BABYLON.serializeAsColor3("emissive")
  37390. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37391. __decorate([
  37392. BABYLON.serialize()
  37393. ], StandardMaterial.prototype, "specularPower", void 0);
  37394. __decorate([
  37395. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37396. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37397. __decorate([
  37398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37399. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37400. __decorate([
  37401. BABYLON.serialize("useEmissiveAsIllumination")
  37402. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37403. __decorate([
  37404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37405. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37406. __decorate([
  37407. BABYLON.serialize("linkEmissiveWithDiffuse")
  37408. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37409. __decorate([
  37410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37411. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37412. __decorate([
  37413. BABYLON.serialize("useSpecularOverAlpha")
  37414. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37415. __decorate([
  37416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37417. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37418. __decorate([
  37419. BABYLON.serialize("useReflectionOverAlpha")
  37420. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37421. __decorate([
  37422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37423. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37424. __decorate([
  37425. BABYLON.serialize("disableLighting")
  37426. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37427. __decorate([
  37428. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37429. ], StandardMaterial.prototype, "disableLighting", void 0);
  37430. __decorate([
  37431. BABYLON.serialize("useParallax")
  37432. ], StandardMaterial.prototype, "_useParallax", void 0);
  37433. __decorate([
  37434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37435. ], StandardMaterial.prototype, "useParallax", void 0);
  37436. __decorate([
  37437. BABYLON.serialize("useParallaxOcclusion")
  37438. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37439. __decorate([
  37440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37441. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37442. __decorate([
  37443. BABYLON.serialize()
  37444. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37445. __decorate([
  37446. BABYLON.serialize("roughness")
  37447. ], StandardMaterial.prototype, "_roughness", void 0);
  37448. __decorate([
  37449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37450. ], StandardMaterial.prototype, "roughness", void 0);
  37451. __decorate([
  37452. BABYLON.serialize()
  37453. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37454. __decorate([
  37455. BABYLON.serialize()
  37456. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37457. __decorate([
  37458. BABYLON.serialize("useLightmapAsShadowmap")
  37459. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37460. __decorate([
  37461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37462. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37463. __decorate([
  37464. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37465. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37466. __decorate([
  37467. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37468. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37469. __decorate([
  37470. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37471. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37472. __decorate([
  37473. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37474. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37475. __decorate([
  37476. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37477. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37478. __decorate([
  37479. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37480. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37481. __decorate([
  37482. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37483. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37484. __decorate([
  37485. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37486. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37487. __decorate([
  37488. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37489. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37490. __decorate([
  37491. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37492. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37493. __decorate([
  37494. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37495. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37496. __decorate([
  37497. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37498. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37499. __decorate([
  37500. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37501. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37502. __decorate([
  37503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37504. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37505. __decorate([
  37506. BABYLON.serialize("maxSimultaneousLights")
  37507. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37508. __decorate([
  37509. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37510. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37511. __decorate([
  37512. BABYLON.serialize("invertNormalMapX")
  37513. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37514. __decorate([
  37515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37516. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37517. __decorate([
  37518. BABYLON.serialize("invertNormalMapY")
  37519. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37520. __decorate([
  37521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37522. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37523. __decorate([
  37524. BABYLON.serialize("twoSidedLighting")
  37525. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37526. __decorate([
  37527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37528. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37529. __decorate([
  37530. BABYLON.serialize()
  37531. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37532. return StandardMaterial;
  37533. }(BABYLON.PushMaterial));
  37534. BABYLON.StandardMaterial = StandardMaterial;
  37535. })(BABYLON || (BABYLON = {}));
  37536. //# sourceMappingURL=babylon.standardMaterial.js.map
  37537. var BABYLON;
  37538. (function (BABYLON) {
  37539. var PBRMaterialDefines = /** @class */ (function (_super) {
  37540. __extends(PBRMaterialDefines, _super);
  37541. function PBRMaterialDefines() {
  37542. var _this = _super.call(this) || this;
  37543. _this.PBR = true;
  37544. _this.MAINUV1 = false;
  37545. _this.MAINUV2 = false;
  37546. _this.UV1 = false;
  37547. _this.UV2 = false;
  37548. _this.ALBEDO = false;
  37549. _this.ALBEDODIRECTUV = 0;
  37550. _this.VERTEXCOLOR = false;
  37551. _this.AMBIENT = false;
  37552. _this.AMBIENTDIRECTUV = 0;
  37553. _this.AMBIENTINGRAYSCALE = false;
  37554. _this.OPACITY = false;
  37555. _this.VERTEXALPHA = false;
  37556. _this.OPACITYDIRECTUV = 0;
  37557. _this.OPACITYRGB = false;
  37558. _this.ALPHATEST = false;
  37559. _this.DEPTHPREPASS = false;
  37560. _this.ALPHABLEND = false;
  37561. _this.ALPHAFROMALBEDO = false;
  37562. _this.ALPHATESTVALUE = 0.5;
  37563. _this.SPECULAROVERALPHA = false;
  37564. _this.RADIANCEOVERALPHA = false;
  37565. _this.ALPHAFRESNEL = false;
  37566. _this.LINEARALPHAFRESNEL = false;
  37567. _this.PREMULTIPLYALPHA = false;
  37568. _this.EMISSIVE = false;
  37569. _this.EMISSIVEDIRECTUV = 0;
  37570. _this.REFLECTIVITY = false;
  37571. _this.REFLECTIVITYDIRECTUV = 0;
  37572. _this.SPECULARTERM = false;
  37573. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37574. _this.MICROSURFACEAUTOMATIC = false;
  37575. _this.LODBASEDMICROSFURACE = false;
  37576. _this.MICROSURFACEMAP = false;
  37577. _this.MICROSURFACEMAPDIRECTUV = 0;
  37578. _this.METALLICWORKFLOW = false;
  37579. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37580. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37581. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37582. _this.AOSTOREINMETALMAPRED = false;
  37583. _this.ENVIRONMENTBRDF = false;
  37584. _this.NORMAL = false;
  37585. _this.TANGENT = false;
  37586. _this.BUMP = false;
  37587. _this.BUMPDIRECTUV = 0;
  37588. _this.PARALLAX = false;
  37589. _this.PARALLAXOCCLUSION = false;
  37590. _this.NORMALXYSCALE = true;
  37591. _this.LIGHTMAP = false;
  37592. _this.LIGHTMAPDIRECTUV = 0;
  37593. _this.USELIGHTMAPASSHADOWMAP = false;
  37594. _this.REFLECTION = false;
  37595. _this.REFLECTIONMAP_3D = false;
  37596. _this.REFLECTIONMAP_SPHERICAL = false;
  37597. _this.REFLECTIONMAP_PLANAR = false;
  37598. _this.REFLECTIONMAP_CUBIC = false;
  37599. _this.REFLECTIONMAP_PROJECTION = false;
  37600. _this.REFLECTIONMAP_SKYBOX = false;
  37601. _this.REFLECTIONMAP_EXPLICIT = false;
  37602. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37603. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37604. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37605. _this.INVERTCUBICMAP = false;
  37606. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37607. _this.USESPHERICALINVERTEX = false;
  37608. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37609. _this.LODINREFLECTIONALPHA = false;
  37610. _this.GAMMAREFLECTION = false;
  37611. _this.RADIANCEOCCLUSION = false;
  37612. _this.HORIZONOCCLUSION = false;
  37613. _this.REFRACTION = false;
  37614. _this.REFRACTIONMAP_3D = false;
  37615. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37616. _this.LODINREFRACTIONALPHA = false;
  37617. _this.GAMMAREFRACTION = false;
  37618. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37619. _this.INSTANCES = false;
  37620. _this.NUM_BONE_INFLUENCERS = 0;
  37621. _this.BonesPerMesh = 0;
  37622. _this.NONUNIFORMSCALING = false;
  37623. _this.MORPHTARGETS = false;
  37624. _this.MORPHTARGETS_NORMAL = false;
  37625. _this.MORPHTARGETS_TANGENT = false;
  37626. _this.NUM_MORPH_INFLUENCERS = 0;
  37627. _this.IMAGEPROCESSING = false;
  37628. _this.VIGNETTE = false;
  37629. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37630. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37631. _this.TONEMAPPING = false;
  37632. _this.CONTRAST = false;
  37633. _this.COLORCURVES = false;
  37634. _this.COLORGRADING = false;
  37635. _this.COLORGRADING3D = false;
  37636. _this.SAMPLER3DGREENDEPTH = false;
  37637. _this.SAMPLER3DBGRMAP = false;
  37638. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37639. _this.EXPOSURE = false;
  37640. _this.USEPHYSICALLIGHTFALLOFF = false;
  37641. _this.TWOSIDEDLIGHTING = false;
  37642. _this.SHADOWFLOAT = false;
  37643. _this.CLIPPLANE = false;
  37644. _this.POINTSIZE = false;
  37645. _this.FOG = false;
  37646. _this.LOGARITHMICDEPTH = false;
  37647. _this.FORCENORMALFORWARD = false;
  37648. _this.rebuild();
  37649. return _this;
  37650. }
  37651. PBRMaterialDefines.prototype.reset = function () {
  37652. _super.prototype.reset.call(this);
  37653. this.ALPHATESTVALUE = 0.5;
  37654. this.PBR = true;
  37655. };
  37656. return PBRMaterialDefines;
  37657. }(BABYLON.MaterialDefines));
  37658. /**
  37659. * The Physically based material base class of BJS.
  37660. *
  37661. * This offers the main features of a standard PBR material.
  37662. * For more information, please refer to the documentation :
  37663. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37664. */
  37665. var PBRBaseMaterial = /** @class */ (function (_super) {
  37666. __extends(PBRBaseMaterial, _super);
  37667. /**
  37668. * Instantiates a new PBRMaterial instance.
  37669. *
  37670. * @param name The material name
  37671. * @param scene The scene the material will be use in.
  37672. */
  37673. function PBRBaseMaterial(name, scene) {
  37674. var _this = _super.call(this, name, scene) || this;
  37675. /**
  37676. * Intensity of the direct lights e.g. the four lights available in your scene.
  37677. * This impacts both the direct diffuse and specular highlights.
  37678. */
  37679. _this._directIntensity = 1.0;
  37680. /**
  37681. * Intensity of the emissive part of the material.
  37682. * This helps controlling the emissive effect without modifying the emissive color.
  37683. */
  37684. _this._emissiveIntensity = 1.0;
  37685. /**
  37686. * Intensity of the environment e.g. how much the environment will light the object
  37687. * either through harmonics for rough material or through the refelction for shiny ones.
  37688. */
  37689. _this._environmentIntensity = 1.0;
  37690. /**
  37691. * This is a special control allowing the reduction of the specular highlights coming from the
  37692. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37693. */
  37694. _this._specularIntensity = 1.0;
  37695. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37696. /**
  37697. * Debug Control allowing disabling the bump map on this material.
  37698. */
  37699. _this._disableBumpMap = false;
  37700. /**
  37701. * AKA Occlusion Texture Intensity in other nomenclature.
  37702. */
  37703. _this._ambientTextureStrength = 1.0;
  37704. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37705. /**
  37706. * AKA Diffuse Color in other nomenclature.
  37707. */
  37708. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37709. /**
  37710. * AKA Specular Color in other nomenclature.
  37711. */
  37712. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37713. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37714. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37715. /**
  37716. * AKA Glossiness in other nomenclature.
  37717. */
  37718. _this._microSurface = 0.9;
  37719. /**
  37720. * source material index of refraction (IOR)' / 'destination material IOR.
  37721. */
  37722. _this._indexOfRefraction = 0.66;
  37723. /**
  37724. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37725. */
  37726. _this._invertRefractionY = false;
  37727. /**
  37728. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37729. * Materials half opaque for instance using refraction could benefit from this control.
  37730. */
  37731. _this._linkRefractionWithTransparency = false;
  37732. _this._useLightmapAsShadowmap = false;
  37733. /**
  37734. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37735. * makes the reflect vector face the model (under horizon).
  37736. */
  37737. _this._useHorizonOcclusion = true;
  37738. /**
  37739. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37740. * too much the area relying on ambient texture to define their ambient occlusion.
  37741. */
  37742. _this._useRadianceOcclusion = true;
  37743. /**
  37744. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37745. */
  37746. _this._useAlphaFromAlbedoTexture = false;
  37747. /**
  37748. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37749. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37750. */
  37751. _this._useSpecularOverAlpha = true;
  37752. /**
  37753. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37754. */
  37755. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37756. /**
  37757. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37758. */
  37759. _this._useRoughnessFromMetallicTextureAlpha = true;
  37760. /**
  37761. * Specifies if the metallic texture contains the roughness information in its green channel.
  37762. */
  37763. _this._useRoughnessFromMetallicTextureGreen = false;
  37764. /**
  37765. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37766. */
  37767. _this._useMetallnessFromMetallicTextureBlue = false;
  37768. /**
  37769. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37770. */
  37771. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37772. /**
  37773. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37774. */
  37775. _this._useAmbientInGrayScale = false;
  37776. /**
  37777. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37778. * The material will try to infer what glossiness each pixel should be.
  37779. */
  37780. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37781. /**
  37782. * BJS is using an harcoded light falloff based on a manually sets up range.
  37783. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37784. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37785. */
  37786. _this._usePhysicalLightFalloff = true;
  37787. /**
  37788. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37789. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37790. */
  37791. _this._useRadianceOverAlpha = true;
  37792. /**
  37793. * Allows using the bump map in parallax mode.
  37794. */
  37795. _this._useParallax = false;
  37796. /**
  37797. * Allows using the bump map in parallax occlusion mode.
  37798. */
  37799. _this._useParallaxOcclusion = false;
  37800. /**
  37801. * Controls the scale bias of the parallax mode.
  37802. */
  37803. _this._parallaxScaleBias = 0.05;
  37804. /**
  37805. * If sets to true, disables all the lights affecting the material.
  37806. */
  37807. _this._disableLighting = false;
  37808. /**
  37809. * Number of Simultaneous lights allowed on the material.
  37810. */
  37811. _this._maxSimultaneousLights = 4;
  37812. /**
  37813. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37814. */
  37815. _this._invertNormalMapX = false;
  37816. /**
  37817. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37818. */
  37819. _this._invertNormalMapY = false;
  37820. /**
  37821. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37822. */
  37823. _this._twoSidedLighting = false;
  37824. /**
  37825. * Defines the alpha limits in alpha test mode.
  37826. */
  37827. _this._alphaCutOff = 0.4;
  37828. /**
  37829. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37830. */
  37831. _this._forceAlphaTest = false;
  37832. /**
  37833. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37834. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37835. */
  37836. _this._useAlphaFresnel = false;
  37837. /**
  37838. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37839. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37840. */
  37841. _this._useLinearAlphaFresnel = false;
  37842. /**
  37843. * The transparency mode of the material.
  37844. */
  37845. _this._transparencyMode = null;
  37846. /**
  37847. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37848. * from cos thetav and roughness:
  37849. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37850. */
  37851. _this._environmentBRDFTexture = null;
  37852. /**
  37853. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37854. */
  37855. _this._forceIrradianceInFragment = false;
  37856. /**
  37857. * Force normal to face away from face.
  37858. */
  37859. _this._forceNormalForward = false;
  37860. /**
  37861. * Force metallic workflow.
  37862. */
  37863. _this._forceMetallicWorkflow = false;
  37864. _this._renderTargets = new BABYLON.SmartArray(16);
  37865. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37866. // Setup the default processing configuration to the scene.
  37867. _this._attachImageProcessingConfiguration(null);
  37868. _this.getRenderTargetTextures = function () {
  37869. _this._renderTargets.reset();
  37870. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37871. _this._renderTargets.push(_this._reflectionTexture);
  37872. }
  37873. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37874. _this._renderTargets.push(_this._refractionTexture);
  37875. }
  37876. return _this._renderTargets;
  37877. };
  37878. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37879. return _this;
  37880. }
  37881. /**
  37882. * Attaches a new image processing configuration to the PBR Material.
  37883. * @param configuration
  37884. */
  37885. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37886. var _this = this;
  37887. if (configuration === this._imageProcessingConfiguration) {
  37888. return;
  37889. }
  37890. // Detaches observer.
  37891. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37892. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37893. }
  37894. // Pick the scene configuration if needed.
  37895. if (!configuration) {
  37896. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37897. }
  37898. else {
  37899. this._imageProcessingConfiguration = configuration;
  37900. }
  37901. // Attaches observer.
  37902. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37903. _this._markAllSubMeshesAsImageProcessingDirty();
  37904. });
  37905. };
  37906. PBRBaseMaterial.prototype.getClassName = function () {
  37907. return "PBRBaseMaterial";
  37908. };
  37909. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37910. get: function () {
  37911. return this._useLogarithmicDepth;
  37912. },
  37913. set: function (value) {
  37914. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37915. },
  37916. enumerable: true,
  37917. configurable: true
  37918. });
  37919. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  37920. /**
  37921. * Gets the current transparency mode.
  37922. */
  37923. get: function () {
  37924. return this._transparencyMode;
  37925. },
  37926. /**
  37927. * Sets the transparency mode of the material.
  37928. */
  37929. set: function (value) {
  37930. if (this._transparencyMode === value) {
  37931. return;
  37932. }
  37933. this._transparencyMode = value;
  37934. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  37935. this._markAllSubMeshesAsTexturesDirty();
  37936. },
  37937. enumerable: true,
  37938. configurable: true
  37939. });
  37940. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  37941. /**
  37942. * Returns true if alpha blending should be disabled.
  37943. */
  37944. get: function () {
  37945. return (this._linkRefractionWithTransparency ||
  37946. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  37947. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37948. },
  37949. enumerable: true,
  37950. configurable: true
  37951. });
  37952. /**
  37953. * Specifies whether or not this material should be rendered in alpha blend mode.
  37954. */
  37955. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37956. if (this._disableAlphaBlending) {
  37957. return false;
  37958. }
  37959. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37960. };
  37961. /**
  37962. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  37963. */
  37964. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  37965. if (this._disableAlphaBlending) {
  37966. return false;
  37967. }
  37968. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  37969. };
  37970. /**
  37971. * Specifies whether or not this material should be rendered in alpha test mode.
  37972. */
  37973. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37974. if (this._forceAlphaTest) {
  37975. return true;
  37976. }
  37977. if (this._linkRefractionWithTransparency) {
  37978. return false;
  37979. }
  37980. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37981. };
  37982. /**
  37983. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  37984. */
  37985. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37986. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37987. };
  37988. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37989. return this._albedoTexture;
  37990. };
  37991. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37992. var _this = this;
  37993. if (subMesh.effect && this.isFrozen) {
  37994. if (this._wasPreviouslyReady) {
  37995. return true;
  37996. }
  37997. }
  37998. if (!subMesh._materialDefines) {
  37999. subMesh._materialDefines = new PBRMaterialDefines();
  38000. }
  38001. var scene = this.getScene();
  38002. var defines = subMesh._materialDefines;
  38003. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38004. if (defines._renderId === scene.getRenderId()) {
  38005. return true;
  38006. }
  38007. }
  38008. var engine = scene.getEngine();
  38009. // Lights
  38010. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38011. defines._needNormals = true;
  38012. // Textures
  38013. if (defines._areTexturesDirty) {
  38014. defines._needUVs = false;
  38015. if (scene.texturesEnabled) {
  38016. if (scene.getEngine().getCaps().textureLOD) {
  38017. defines.LODBASEDMICROSFURACE = true;
  38018. }
  38019. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38020. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38021. return false;
  38022. }
  38023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38024. }
  38025. else {
  38026. defines.ALBEDO = false;
  38027. }
  38028. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38029. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38030. return false;
  38031. }
  38032. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38033. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38034. }
  38035. else {
  38036. defines.AMBIENT = false;
  38037. }
  38038. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38039. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38040. return false;
  38041. }
  38042. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38043. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38044. }
  38045. else {
  38046. defines.OPACITY = false;
  38047. }
  38048. var reflectionTexture = this._getReflectionTexture();
  38049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38050. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38051. return false;
  38052. }
  38053. defines.REFLECTION = true;
  38054. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38055. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38056. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38057. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38058. defines.INVERTCUBICMAP = true;
  38059. }
  38060. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38061. switch (reflectionTexture.coordinatesMode) {
  38062. case BABYLON.Texture.CUBIC_MODE:
  38063. case BABYLON.Texture.INVCUBIC_MODE:
  38064. defines.REFLECTIONMAP_CUBIC = true;
  38065. break;
  38066. case BABYLON.Texture.EXPLICIT_MODE:
  38067. defines.REFLECTIONMAP_EXPLICIT = true;
  38068. break;
  38069. case BABYLON.Texture.PLANAR_MODE:
  38070. defines.REFLECTIONMAP_PLANAR = true;
  38071. break;
  38072. case BABYLON.Texture.PROJECTION_MODE:
  38073. defines.REFLECTIONMAP_PROJECTION = true;
  38074. break;
  38075. case BABYLON.Texture.SKYBOX_MODE:
  38076. defines.REFLECTIONMAP_SKYBOX = true;
  38077. break;
  38078. case BABYLON.Texture.SPHERICAL_MODE:
  38079. defines.REFLECTIONMAP_SPHERICAL = true;
  38080. break;
  38081. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38082. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38083. break;
  38084. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38085. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38086. break;
  38087. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38088. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38089. break;
  38090. }
  38091. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38092. if (reflectionTexture.sphericalPolynomial) {
  38093. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38094. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38095. defines.USESPHERICALINVERTEX = false;
  38096. }
  38097. else {
  38098. defines.USESPHERICALINVERTEX = true;
  38099. }
  38100. }
  38101. }
  38102. }
  38103. else {
  38104. defines.REFLECTION = false;
  38105. defines.REFLECTIONMAP_3D = false;
  38106. defines.REFLECTIONMAP_SPHERICAL = false;
  38107. defines.REFLECTIONMAP_PLANAR = false;
  38108. defines.REFLECTIONMAP_CUBIC = false;
  38109. defines.REFLECTIONMAP_PROJECTION = false;
  38110. defines.REFLECTIONMAP_SKYBOX = false;
  38111. defines.REFLECTIONMAP_EXPLICIT = false;
  38112. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38113. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38114. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38115. defines.INVERTCUBICMAP = false;
  38116. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38117. defines.USESPHERICALINVERTEX = false;
  38118. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38119. defines.LODINREFLECTIONALPHA = false;
  38120. defines.GAMMAREFLECTION = false;
  38121. }
  38122. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38123. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38124. return false;
  38125. }
  38126. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38127. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38128. }
  38129. else {
  38130. defines.LIGHTMAP = false;
  38131. }
  38132. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38133. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38134. return false;
  38135. }
  38136. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38137. }
  38138. else {
  38139. defines.EMISSIVE = false;
  38140. }
  38141. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38142. if (this._metallicTexture) {
  38143. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38144. return false;
  38145. }
  38146. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38147. defines.METALLICWORKFLOW = true;
  38148. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38149. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38150. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38151. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38152. }
  38153. else if (this._reflectivityTexture) {
  38154. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38155. return false;
  38156. }
  38157. defines.METALLICWORKFLOW = false;
  38158. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38159. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38160. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38161. }
  38162. else {
  38163. defines.METALLICWORKFLOW = false;
  38164. defines.REFLECTIVITY = false;
  38165. }
  38166. if (this._microSurfaceTexture) {
  38167. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38168. return false;
  38169. }
  38170. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38171. }
  38172. else {
  38173. defines.MICROSURFACEMAP = false;
  38174. }
  38175. }
  38176. else {
  38177. defines.REFLECTIVITY = false;
  38178. defines.MICROSURFACEMAP = false;
  38179. }
  38180. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38181. // Bump texure can not be none blocking.
  38182. if (!this._bumpTexture.isReady()) {
  38183. return false;
  38184. }
  38185. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38186. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38187. defines.PARALLAX = true;
  38188. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38189. }
  38190. else {
  38191. defines.PARALLAX = false;
  38192. }
  38193. }
  38194. else {
  38195. defines.BUMP = false;
  38196. }
  38197. var refractionTexture = this._getRefractionTexture();
  38198. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38199. if (!refractionTexture.isReadyOrNotBlocking()) {
  38200. return false;
  38201. }
  38202. defines.REFRACTION = true;
  38203. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38204. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38205. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38206. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38207. if (this._linkRefractionWithTransparency) {
  38208. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38209. }
  38210. }
  38211. else {
  38212. defines.REFRACTION = false;
  38213. }
  38214. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38215. // This is blocking.
  38216. if (!this._environmentBRDFTexture.isReady()) {
  38217. return false;
  38218. }
  38219. defines.ENVIRONMENTBRDF = true;
  38220. }
  38221. else {
  38222. defines.ENVIRONMENTBRDF = false;
  38223. }
  38224. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38225. defines.ALPHAFROMALBEDO = true;
  38226. }
  38227. else {
  38228. defines.ALPHAFROMALBEDO = false;
  38229. }
  38230. }
  38231. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38232. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38233. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38234. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38235. defines.METALLICWORKFLOW = true;
  38236. }
  38237. else {
  38238. defines.METALLICWORKFLOW = false;
  38239. }
  38240. if (!this.backFaceCulling && this._twoSidedLighting) {
  38241. defines.TWOSIDEDLIGHTING = true;
  38242. }
  38243. else {
  38244. defines.TWOSIDEDLIGHTING = false;
  38245. }
  38246. defines.ALPHATESTVALUE = this._alphaCutOff;
  38247. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38248. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38249. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38250. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38251. }
  38252. if (defines._areImageProcessingDirty) {
  38253. if (!this._imageProcessingConfiguration.isReady()) {
  38254. return false;
  38255. }
  38256. this._imageProcessingConfiguration.prepareDefines(defines);
  38257. }
  38258. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38259. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38260. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38261. // Misc.
  38262. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  38263. // Values that need to be evaluated on every frame
  38264. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  38265. // Attribs
  38266. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38267. var bufferMesh = null;
  38268. if (mesh instanceof BABYLON.InstancedMesh) {
  38269. bufferMesh = mesh.sourceMesh;
  38270. }
  38271. else if (mesh instanceof BABYLON.Mesh) {
  38272. bufferMesh = mesh;
  38273. }
  38274. if (bufferMesh) {
  38275. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38276. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38277. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38278. var normals = normalVertexBuffer.getData();
  38279. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38280. var strideSize = normalVertexBuffer.getStrideSize();
  38281. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38282. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38283. defines.NORMAL = false;
  38284. }
  38285. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38286. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38287. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38288. var tangents = tangentVertexBuffer.getData();
  38289. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38290. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38291. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38292. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38293. defines.TANGENT = false;
  38294. }
  38295. }
  38296. }
  38297. else {
  38298. if (!scene.getEngine().getCaps().standardDerivatives) {
  38299. bufferMesh.createNormals(true);
  38300. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38301. }
  38302. }
  38303. }
  38304. }
  38305. // Get correct effect
  38306. if (defines.isDirty) {
  38307. defines.markAsProcessed();
  38308. scene.resetCachedMaterial();
  38309. // Fallbacks
  38310. var fallbacks = new BABYLON.EffectFallbacks();
  38311. var fallbackRank = 0;
  38312. if (defines.USESPHERICALINVERTEX) {
  38313. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38314. }
  38315. if (defines.FOG) {
  38316. fallbacks.addFallback(fallbackRank, "FOG");
  38317. }
  38318. if (defines.POINTSIZE) {
  38319. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38320. }
  38321. if (defines.LOGARITHMICDEPTH) {
  38322. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38323. }
  38324. if (defines.PARALLAX) {
  38325. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38326. }
  38327. if (defines.PARALLAXOCCLUSION) {
  38328. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38329. }
  38330. if (defines.ENVIRONMENTBRDF) {
  38331. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38332. }
  38333. if (defines.TANGENT) {
  38334. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38335. }
  38336. if (defines.BUMP) {
  38337. fallbacks.addFallback(fallbackRank++, "BUMP");
  38338. }
  38339. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38340. if (defines.SPECULARTERM) {
  38341. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38342. }
  38343. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38344. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38345. }
  38346. if (defines.LIGHTMAP) {
  38347. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38348. }
  38349. if (defines.NORMAL) {
  38350. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38351. }
  38352. if (defines.AMBIENT) {
  38353. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38354. }
  38355. if (defines.EMISSIVE) {
  38356. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38357. }
  38358. if (defines.VERTEXCOLOR) {
  38359. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38360. }
  38361. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38362. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38363. }
  38364. if (defines.MORPHTARGETS) {
  38365. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38366. }
  38367. //Attributes
  38368. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38369. if (defines.NORMAL) {
  38370. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38371. }
  38372. if (defines.TANGENT) {
  38373. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38374. }
  38375. if (defines.UV1) {
  38376. attribs.push(BABYLON.VertexBuffer.UVKind);
  38377. }
  38378. if (defines.UV2) {
  38379. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38380. }
  38381. if (defines.VERTEXCOLOR) {
  38382. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38383. }
  38384. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38385. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38386. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38387. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38388. "vFogInfos", "vFogColor", "pointSize",
  38389. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38390. "mBones",
  38391. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38392. "vLightingIntensity",
  38393. "logarithmicDepthConstant",
  38394. "vSphericalX", "vSphericalY", "vSphericalZ",
  38395. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38396. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38397. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38398. "vTangentSpaceParams"
  38399. ];
  38400. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38401. "bumpSampler", "lightmapSampler", "opacitySampler",
  38402. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38403. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38404. "microSurfaceSampler", "environmentBrdfSampler"];
  38405. var uniformBuffers = ["Material", "Scene"];
  38406. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38407. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38408. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38409. uniformsNames: uniforms,
  38410. uniformBuffersNames: uniformBuffers,
  38411. samplers: samplers,
  38412. defines: defines,
  38413. maxSimultaneousLights: this._maxSimultaneousLights
  38414. });
  38415. var onCompiled = function (effect) {
  38416. if (_this.onCompiled) {
  38417. _this.onCompiled(effect);
  38418. }
  38419. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38420. };
  38421. var join = defines.toString();
  38422. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38423. attributes: attribs,
  38424. uniformsNames: uniforms,
  38425. uniformBuffersNames: uniformBuffers,
  38426. samplers: samplers,
  38427. defines: join,
  38428. fallbacks: fallbacks,
  38429. onCompiled: onCompiled,
  38430. onError: this.onError,
  38431. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38432. }, engine), defines);
  38433. this.buildUniformLayout();
  38434. }
  38435. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38436. return false;
  38437. }
  38438. defines._renderId = scene.getRenderId();
  38439. this._wasPreviouslyReady = true;
  38440. return true;
  38441. };
  38442. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38443. // Order is important !
  38444. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38445. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38446. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38447. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38448. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38449. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38450. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38451. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38452. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38453. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38454. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38455. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38456. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38457. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38458. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38459. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38460. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38461. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38462. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38463. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38464. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38465. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38466. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38467. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38468. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38469. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38470. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38471. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38472. this._uniformBuffer.addUniform("pointSize", 1);
  38473. this._uniformBuffer.create();
  38474. };
  38475. PBRBaseMaterial.prototype.unbind = function () {
  38476. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38477. this._uniformBuffer.setTexture("reflectionSampler", null);
  38478. }
  38479. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38480. this._uniformBuffer.setTexture("refractionSampler", null);
  38481. }
  38482. _super.prototype.unbind.call(this);
  38483. };
  38484. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38485. this._activeEffect.setMatrix("world", world);
  38486. };
  38487. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38488. var scene = this.getScene();
  38489. var defines = subMesh._materialDefines;
  38490. if (!defines) {
  38491. return;
  38492. }
  38493. var effect = subMesh.effect;
  38494. if (!effect) {
  38495. return;
  38496. }
  38497. this._activeEffect = effect;
  38498. // Matrices
  38499. this.bindOnlyWorldMatrix(world);
  38500. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38501. // Bones
  38502. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38503. var reflectionTexture = null;
  38504. if (mustRebind) {
  38505. this._uniformBuffer.bindToEffect(effect, "Material");
  38506. this.bindViewProjection(effect);
  38507. reflectionTexture = this._getReflectionTexture();
  38508. var refractionTexture = this._getRefractionTexture();
  38509. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38510. // Texture uniforms
  38511. if (scene.texturesEnabled) {
  38512. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38513. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38514. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38515. }
  38516. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38517. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38518. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38519. }
  38520. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38521. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38522. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38523. }
  38524. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38525. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38526. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38527. var polynomials = reflectionTexture.sphericalPolynomial;
  38528. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38529. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38530. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38531. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38532. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38533. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38534. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38535. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38536. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38537. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38538. }
  38539. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38540. }
  38541. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38542. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38543. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38544. }
  38545. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38546. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38547. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38548. }
  38549. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38550. if (this._metallicTexture) {
  38551. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38552. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38553. }
  38554. else if (this._reflectivityTexture) {
  38555. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38556. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38557. }
  38558. if (this._microSurfaceTexture) {
  38559. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38560. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38561. }
  38562. }
  38563. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38564. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38565. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38566. if (scene._mirroredCameraPosition) {
  38567. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38568. }
  38569. else {
  38570. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38571. }
  38572. }
  38573. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38574. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38575. var depth = 1.0;
  38576. if (!refractionTexture.isCube) {
  38577. if (refractionTexture.depth) {
  38578. depth = refractionTexture.depth;
  38579. }
  38580. }
  38581. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38582. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38583. }
  38584. }
  38585. // Point size
  38586. if (this.pointsCloud) {
  38587. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38588. }
  38589. // Colors
  38590. if (defines.METALLICWORKFLOW) {
  38591. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38592. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38593. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38594. }
  38595. else {
  38596. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38597. }
  38598. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38599. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38600. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38601. // Misc
  38602. this._lightingInfos.x = this._directIntensity;
  38603. this._lightingInfos.y = this._emissiveIntensity;
  38604. this._lightingInfos.z = this._environmentIntensity;
  38605. this._lightingInfos.w = this._specularIntensity;
  38606. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38607. }
  38608. // Textures
  38609. if (scene.texturesEnabled) {
  38610. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38611. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38612. }
  38613. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38614. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38615. }
  38616. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38617. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38618. }
  38619. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38620. if (defines.LODBASEDMICROSFURACE) {
  38621. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38622. }
  38623. else {
  38624. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38625. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38626. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38627. }
  38628. }
  38629. if (defines.ENVIRONMENTBRDF) {
  38630. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38631. }
  38632. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38633. if (defines.LODBASEDMICROSFURACE) {
  38634. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  38635. }
  38636. else {
  38637. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  38638. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  38639. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  38640. }
  38641. }
  38642. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38643. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  38644. }
  38645. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38646. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  38647. }
  38648. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38649. if (this._metallicTexture) {
  38650. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  38651. }
  38652. else if (this._reflectivityTexture) {
  38653. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  38654. }
  38655. if (this._microSurfaceTexture) {
  38656. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  38657. }
  38658. }
  38659. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38660. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  38661. }
  38662. }
  38663. // Clip plane
  38664. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  38665. // Colors
  38666. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  38667. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38668. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  38669. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  38670. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38671. }
  38672. if (mustRebind || !this.isFrozen) {
  38673. // Lights
  38674. if (scene.lightsEnabled && !this._disableLighting) {
  38675. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  38676. }
  38677. // View
  38678. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  38679. this.bindView(effect);
  38680. }
  38681. // Fog
  38682. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  38683. // Morph targets
  38684. if (defines.NUM_MORPH_INFLUENCERS) {
  38685. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  38686. }
  38687. // image processing
  38688. this._imageProcessingConfiguration.bind(this._activeEffect);
  38689. // Log. depth
  38690. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  38691. }
  38692. this._uniformBuffer.update();
  38693. this._afterBind(mesh);
  38694. };
  38695. PBRBaseMaterial.prototype.getAnimatables = function () {
  38696. var results = [];
  38697. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  38698. results.push(this._albedoTexture);
  38699. }
  38700. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38701. results.push(this._ambientTexture);
  38702. }
  38703. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38704. results.push(this._opacityTexture);
  38705. }
  38706. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38707. results.push(this._reflectionTexture);
  38708. }
  38709. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38710. results.push(this._emissiveTexture);
  38711. }
  38712. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  38713. results.push(this._metallicTexture);
  38714. }
  38715. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  38716. results.push(this._reflectivityTexture);
  38717. }
  38718. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38719. results.push(this._bumpTexture);
  38720. }
  38721. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38722. results.push(this._lightmapTexture);
  38723. }
  38724. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38725. results.push(this._refractionTexture);
  38726. }
  38727. return results;
  38728. };
  38729. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38730. if (this._reflectionTexture) {
  38731. return this._reflectionTexture;
  38732. }
  38733. return this.getScene().environmentTexture;
  38734. };
  38735. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38736. if (this._refractionTexture) {
  38737. return this._refractionTexture;
  38738. }
  38739. if (this._linkRefractionWithTransparency) {
  38740. return this.getScene().environmentTexture;
  38741. }
  38742. return null;
  38743. };
  38744. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38745. if (forceDisposeTextures) {
  38746. if (this._albedoTexture) {
  38747. this._albedoTexture.dispose();
  38748. }
  38749. if (this._ambientTexture) {
  38750. this._ambientTexture.dispose();
  38751. }
  38752. if (this._opacityTexture) {
  38753. this._opacityTexture.dispose();
  38754. }
  38755. if (this._reflectionTexture) {
  38756. this._reflectionTexture.dispose();
  38757. }
  38758. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  38759. this._environmentBRDFTexture.dispose();
  38760. }
  38761. if (this._emissiveTexture) {
  38762. this._emissiveTexture.dispose();
  38763. }
  38764. if (this._metallicTexture) {
  38765. this._metallicTexture.dispose();
  38766. }
  38767. if (this._reflectivityTexture) {
  38768. this._reflectivityTexture.dispose();
  38769. }
  38770. if (this._bumpTexture) {
  38771. this._bumpTexture.dispose();
  38772. }
  38773. if (this._lightmapTexture) {
  38774. this._lightmapTexture.dispose();
  38775. }
  38776. if (this._refractionTexture) {
  38777. this._refractionTexture.dispose();
  38778. }
  38779. }
  38780. this._renderTargets.dispose();
  38781. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38782. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38783. }
  38784. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38785. };
  38786. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38787. __decorate([
  38788. BABYLON.serializeAsImageProcessingConfiguration()
  38789. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38790. __decorate([
  38791. BABYLON.serialize()
  38792. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38793. __decorate([
  38794. BABYLON.serialize()
  38795. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  38796. return PBRBaseMaterial;
  38797. }(BABYLON.PushMaterial));
  38798. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38799. })(BABYLON || (BABYLON = {}));
  38800. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38801. var BABYLON;
  38802. (function (BABYLON) {
  38803. /**
  38804. * The Physically based simple base material of BJS.
  38805. *
  38806. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38807. * It is used as the base class for both the specGloss and metalRough conventions.
  38808. */
  38809. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  38810. __extends(PBRBaseSimpleMaterial, _super);
  38811. /**
  38812. * Instantiates a new PBRMaterial instance.
  38813. *
  38814. * @param name The material name
  38815. * @param scene The scene the material will be use in.
  38816. */
  38817. function PBRBaseSimpleMaterial(name, scene) {
  38818. var _this = _super.call(this, name, scene) || this;
  38819. /**
  38820. * Number of Simultaneous lights allowed on the material.
  38821. */
  38822. _this.maxSimultaneousLights = 4;
  38823. /**
  38824. * If sets to true, disables all the lights affecting the material.
  38825. */
  38826. _this.disableLighting = false;
  38827. /**
  38828. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38829. */
  38830. _this.invertNormalMapX = false;
  38831. /**
  38832. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38833. */
  38834. _this.invertNormalMapY = false;
  38835. /**
  38836. * Emissivie color used to self-illuminate the model.
  38837. */
  38838. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38839. /**
  38840. * Occlusion Channel Strenght.
  38841. */
  38842. _this.occlusionStrength = 1.0;
  38843. _this.useLightmapAsShadowmap = false;
  38844. _this._useAlphaFromAlbedoTexture = true;
  38845. _this._useAmbientInGrayScale = true;
  38846. return _this;
  38847. }
  38848. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38849. /**
  38850. * Gets the current double sided mode.
  38851. */
  38852. get: function () {
  38853. return this._twoSidedLighting;
  38854. },
  38855. /**
  38856. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38857. */
  38858. set: function (value) {
  38859. if (this._twoSidedLighting === value) {
  38860. return;
  38861. }
  38862. this._twoSidedLighting = value;
  38863. this.backFaceCulling = !value;
  38864. this._markAllSubMeshesAsTexturesDirty();
  38865. },
  38866. enumerable: true,
  38867. configurable: true
  38868. });
  38869. /**
  38870. * Return the active textures of the material.
  38871. */
  38872. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38873. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38874. if (this.environmentTexture) {
  38875. activeTextures.push(this.environmentTexture);
  38876. }
  38877. if (this.normalTexture) {
  38878. activeTextures.push(this.normalTexture);
  38879. }
  38880. if (this.emissiveTexture) {
  38881. activeTextures.push(this.emissiveTexture);
  38882. }
  38883. if (this.occlusionTexture) {
  38884. activeTextures.push(this.occlusionTexture);
  38885. }
  38886. if (this.lightmapTexture) {
  38887. activeTextures.push(this.lightmapTexture);
  38888. }
  38889. return activeTextures;
  38890. };
  38891. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  38892. if (_super.prototype.hasTexture.call(this, texture)) {
  38893. return true;
  38894. }
  38895. if (this.lightmapTexture === texture) {
  38896. return true;
  38897. }
  38898. return false;
  38899. };
  38900. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38901. return "PBRBaseSimpleMaterial";
  38902. };
  38903. __decorate([
  38904. BABYLON.serialize(),
  38905. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38906. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38907. __decorate([
  38908. BABYLON.serialize(),
  38909. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38910. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38911. __decorate([
  38912. BABYLON.serializeAsTexture(),
  38913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38914. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38915. __decorate([
  38916. BABYLON.serialize(),
  38917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38918. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38919. __decorate([
  38920. BABYLON.serialize(),
  38921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38922. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38923. __decorate([
  38924. BABYLON.serializeAsTexture(),
  38925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38926. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38927. __decorate([
  38928. BABYLON.serializeAsColor3("emissive"),
  38929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38930. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38931. __decorate([
  38932. BABYLON.serializeAsTexture(),
  38933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38934. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38935. __decorate([
  38936. BABYLON.serialize(),
  38937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38938. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38939. __decorate([
  38940. BABYLON.serializeAsTexture(),
  38941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38942. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38943. __decorate([
  38944. BABYLON.serialize(),
  38945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38946. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38947. __decorate([
  38948. BABYLON.serialize()
  38949. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38950. __decorate([
  38951. BABYLON.serializeAsTexture(),
  38952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38953. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  38954. __decorate([
  38955. BABYLON.serialize(),
  38956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38957. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38958. return PBRBaseSimpleMaterial;
  38959. }(BABYLON.PBRBaseMaterial));
  38960. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38961. })(BABYLON || (BABYLON = {}));
  38962. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38963. var BABYLON;
  38964. (function (BABYLON) {
  38965. /**
  38966. * The Physically based material of BJS.
  38967. *
  38968. * This offers the main features of a standard PBR material.
  38969. * For more information, please refer to the documentation :
  38970. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38971. */
  38972. var PBRMaterial = /** @class */ (function (_super) {
  38973. __extends(PBRMaterial, _super);
  38974. /**
  38975. * Instantiates a new PBRMaterial instance.
  38976. *
  38977. * @param name The material name
  38978. * @param scene The scene the material will be use in.
  38979. */
  38980. function PBRMaterial(name, scene) {
  38981. var _this = _super.call(this, name, scene) || this;
  38982. /**
  38983. * Intensity of the direct lights e.g. the four lights available in your scene.
  38984. * This impacts both the direct diffuse and specular highlights.
  38985. */
  38986. _this.directIntensity = 1.0;
  38987. /**
  38988. * Intensity of the emissive part of the material.
  38989. * This helps controlling the emissive effect without modifying the emissive color.
  38990. */
  38991. _this.emissiveIntensity = 1.0;
  38992. /**
  38993. * Intensity of the environment e.g. how much the environment will light the object
  38994. * either through harmonics for rough material or through the refelction for shiny ones.
  38995. */
  38996. _this.environmentIntensity = 1.0;
  38997. /**
  38998. * This is a special control allowing the reduction of the specular highlights coming from the
  38999. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39000. */
  39001. _this.specularIntensity = 1.0;
  39002. /**
  39003. * Debug Control allowing disabling the bump map on this material.
  39004. */
  39005. _this.disableBumpMap = false;
  39006. /**
  39007. * AKA Occlusion Texture Intensity in other nomenclature.
  39008. */
  39009. _this.ambientTextureStrength = 1.0;
  39010. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39011. /**
  39012. * AKA Diffuse Color in other nomenclature.
  39013. */
  39014. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39015. /**
  39016. * AKA Specular Color in other nomenclature.
  39017. */
  39018. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39019. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39020. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39021. /**
  39022. * AKA Glossiness in other nomenclature.
  39023. */
  39024. _this.microSurface = 1.0;
  39025. /**
  39026. * source material index of refraction (IOR)' / 'destination material IOR.
  39027. */
  39028. _this.indexOfRefraction = 0.66;
  39029. /**
  39030. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39031. */
  39032. _this.invertRefractionY = false;
  39033. /**
  39034. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39035. * Materials half opaque for instance using refraction could benefit from this control.
  39036. */
  39037. _this.linkRefractionWithTransparency = false;
  39038. _this.useLightmapAsShadowmap = false;
  39039. /**
  39040. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39041. */
  39042. _this.useAlphaFromAlbedoTexture = false;
  39043. /**
  39044. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39045. */
  39046. _this.forceAlphaTest = false;
  39047. /**
  39048. * Defines the alpha limits in alpha test mode.
  39049. */
  39050. _this.alphaCutOff = 0.4;
  39051. /**
  39052. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39053. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39054. */
  39055. _this.useSpecularOverAlpha = true;
  39056. /**
  39057. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39058. */
  39059. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39060. /**
  39061. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39062. */
  39063. _this.useRoughnessFromMetallicTextureAlpha = true;
  39064. /**
  39065. * Specifies if the metallic texture contains the roughness information in its green channel.
  39066. */
  39067. _this.useRoughnessFromMetallicTextureGreen = false;
  39068. /**
  39069. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39070. */
  39071. _this.useMetallnessFromMetallicTextureBlue = false;
  39072. /**
  39073. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39074. */
  39075. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39076. /**
  39077. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39078. */
  39079. _this.useAmbientInGrayScale = false;
  39080. /**
  39081. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39082. * The material will try to infer what glossiness each pixel should be.
  39083. */
  39084. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39085. /**
  39086. * BJS is using an harcoded light falloff based on a manually sets up range.
  39087. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39088. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39089. */
  39090. _this.usePhysicalLightFalloff = true;
  39091. /**
  39092. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39093. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39094. */
  39095. _this.useRadianceOverAlpha = true;
  39096. /**
  39097. * Allows using the bump map in parallax mode.
  39098. */
  39099. _this.useParallax = false;
  39100. /**
  39101. * Allows using the bump map in parallax occlusion mode.
  39102. */
  39103. _this.useParallaxOcclusion = false;
  39104. /**
  39105. * Controls the scale bias of the parallax mode.
  39106. */
  39107. _this.parallaxScaleBias = 0.05;
  39108. /**
  39109. * If sets to true, disables all the lights affecting the material.
  39110. */
  39111. _this.disableLighting = false;
  39112. /**
  39113. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39114. */
  39115. _this.forceIrradianceInFragment = false;
  39116. /**
  39117. * Number of Simultaneous lights allowed on the material.
  39118. */
  39119. _this.maxSimultaneousLights = 4;
  39120. /**
  39121. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39122. */
  39123. _this.invertNormalMapX = false;
  39124. /**
  39125. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39126. */
  39127. _this.invertNormalMapY = false;
  39128. /**
  39129. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39130. */
  39131. _this.twoSidedLighting = false;
  39132. /**
  39133. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39134. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39135. */
  39136. _this.useAlphaFresnel = false;
  39137. /**
  39138. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39139. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39140. */
  39141. _this.useLinearAlphaFresnel = false;
  39142. /**
  39143. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39144. * And/Or occlude the blended part.
  39145. */
  39146. _this.environmentBRDFTexture = null;
  39147. /**
  39148. * Force normal to face away from face.
  39149. */
  39150. _this.forceNormalForward = false;
  39151. /**
  39152. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39153. * makes the reflect vector face the model (under horizon).
  39154. */
  39155. _this.useHorizonOcclusion = true;
  39156. /**
  39157. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39158. * too much the area relying on ambient texture to define their ambient occlusion.
  39159. */
  39160. _this.useRadianceOcclusion = true;
  39161. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39162. return _this;
  39163. }
  39164. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39165. /**
  39166. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39167. */
  39168. get: function () {
  39169. return this._PBRMATERIAL_OPAQUE;
  39170. },
  39171. enumerable: true,
  39172. configurable: true
  39173. });
  39174. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39175. /**
  39176. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39177. */
  39178. get: function () {
  39179. return this._PBRMATERIAL_ALPHATEST;
  39180. },
  39181. enumerable: true,
  39182. configurable: true
  39183. });
  39184. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39185. /**
  39186. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39187. */
  39188. get: function () {
  39189. return this._PBRMATERIAL_ALPHABLEND;
  39190. },
  39191. enumerable: true,
  39192. configurable: true
  39193. });
  39194. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39195. /**
  39196. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39197. * They are also discarded below the alpha cutoff threshold to improve performances.
  39198. */
  39199. get: function () {
  39200. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39201. },
  39202. enumerable: true,
  39203. configurable: true
  39204. });
  39205. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39206. /**
  39207. * Gets the image processing configuration used either in this material.
  39208. */
  39209. get: function () {
  39210. return this._imageProcessingConfiguration;
  39211. },
  39212. /**
  39213. * Sets the Default image processing configuration used either in the this material.
  39214. *
  39215. * If sets to null, the scene one is in use.
  39216. */
  39217. set: function (value) {
  39218. this._attachImageProcessingConfiguration(value);
  39219. // Ensure the effect will be rebuilt.
  39220. this._markAllSubMeshesAsTexturesDirty();
  39221. },
  39222. enumerable: true,
  39223. configurable: true
  39224. });
  39225. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39226. /**
  39227. * Gets wether the color curves effect is enabled.
  39228. */
  39229. get: function () {
  39230. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39231. },
  39232. /**
  39233. * Sets wether the color curves effect is enabled.
  39234. */
  39235. set: function (value) {
  39236. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39237. },
  39238. enumerable: true,
  39239. configurable: true
  39240. });
  39241. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39242. /**
  39243. * Gets wether the color grading effect is enabled.
  39244. */
  39245. get: function () {
  39246. return this.imageProcessingConfiguration.colorGradingEnabled;
  39247. },
  39248. /**
  39249. * Gets wether the color grading effect is enabled.
  39250. */
  39251. set: function (value) {
  39252. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39253. },
  39254. enumerable: true,
  39255. configurable: true
  39256. });
  39257. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39258. /**
  39259. * Gets wether tonemapping is enabled or not.
  39260. */
  39261. get: function () {
  39262. return this._imageProcessingConfiguration.toneMappingEnabled;
  39263. },
  39264. /**
  39265. * Sets wether tonemapping is enabled or not
  39266. */
  39267. set: function (value) {
  39268. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39269. },
  39270. enumerable: true,
  39271. configurable: true
  39272. });
  39273. ;
  39274. ;
  39275. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39276. /**
  39277. * The camera exposure used on this material.
  39278. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39279. * This corresponds to a photographic exposure.
  39280. */
  39281. get: function () {
  39282. return this._imageProcessingConfiguration.exposure;
  39283. },
  39284. /**
  39285. * The camera exposure used on this material.
  39286. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39287. * This corresponds to a photographic exposure.
  39288. */
  39289. set: function (value) {
  39290. this._imageProcessingConfiguration.exposure = value;
  39291. },
  39292. enumerable: true,
  39293. configurable: true
  39294. });
  39295. ;
  39296. ;
  39297. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39298. /**
  39299. * Gets The camera contrast used on this material.
  39300. */
  39301. get: function () {
  39302. return this._imageProcessingConfiguration.contrast;
  39303. },
  39304. /**
  39305. * Sets The camera contrast used on this material.
  39306. */
  39307. set: function (value) {
  39308. this._imageProcessingConfiguration.contrast = value;
  39309. },
  39310. enumerable: true,
  39311. configurable: true
  39312. });
  39313. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39314. /**
  39315. * Gets the Color Grading 2D Lookup Texture.
  39316. */
  39317. get: function () {
  39318. return this._imageProcessingConfiguration.colorGradingTexture;
  39319. },
  39320. /**
  39321. * Sets the Color Grading 2D Lookup Texture.
  39322. */
  39323. set: function (value) {
  39324. this._imageProcessingConfiguration.colorGradingTexture = value;
  39325. },
  39326. enumerable: true,
  39327. configurable: true
  39328. });
  39329. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39330. /**
  39331. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39332. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39333. * 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;
  39334. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39335. */
  39336. get: function () {
  39337. return this._imageProcessingConfiguration.colorCurves;
  39338. },
  39339. /**
  39340. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39341. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39342. * 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;
  39343. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39344. */
  39345. set: function (value) {
  39346. this._imageProcessingConfiguration.colorCurves = value;
  39347. },
  39348. enumerable: true,
  39349. configurable: true
  39350. });
  39351. PBRMaterial.prototype.getClassName = function () {
  39352. return "PBRMaterial";
  39353. };
  39354. PBRMaterial.prototype.getActiveTextures = function () {
  39355. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39356. if (this._albedoTexture) {
  39357. activeTextures.push(this._albedoTexture);
  39358. }
  39359. if (this._ambientTexture) {
  39360. activeTextures.push(this._ambientTexture);
  39361. }
  39362. if (this._opacityTexture) {
  39363. activeTextures.push(this._opacityTexture);
  39364. }
  39365. if (this._reflectionTexture) {
  39366. activeTextures.push(this._reflectionTexture);
  39367. }
  39368. if (this._emissiveTexture) {
  39369. activeTextures.push(this._emissiveTexture);
  39370. }
  39371. if (this._reflectivityTexture) {
  39372. activeTextures.push(this._reflectivityTexture);
  39373. }
  39374. if (this._metallicTexture) {
  39375. activeTextures.push(this._metallicTexture);
  39376. }
  39377. if (this._microSurfaceTexture) {
  39378. activeTextures.push(this._microSurfaceTexture);
  39379. }
  39380. if (this._bumpTexture) {
  39381. activeTextures.push(this._bumpTexture);
  39382. }
  39383. if (this._lightmapTexture) {
  39384. activeTextures.push(this._lightmapTexture);
  39385. }
  39386. if (this._refractionTexture) {
  39387. activeTextures.push(this._refractionTexture);
  39388. }
  39389. return activeTextures;
  39390. };
  39391. PBRMaterial.prototype.hasTexture = function (texture) {
  39392. if (_super.prototype.hasTexture.call(this, texture)) {
  39393. return true;
  39394. }
  39395. if (this._albedoTexture === texture) {
  39396. return true;
  39397. }
  39398. if (this._ambientTexture === texture) {
  39399. return true;
  39400. }
  39401. if (this._opacityTexture === texture) {
  39402. return true;
  39403. }
  39404. if (this._reflectionTexture === texture) {
  39405. return true;
  39406. }
  39407. if (this._reflectivityTexture === texture) {
  39408. return true;
  39409. }
  39410. if (this._metallicTexture === texture) {
  39411. return true;
  39412. }
  39413. if (this._microSurfaceTexture === texture) {
  39414. return true;
  39415. }
  39416. if (this._bumpTexture === texture) {
  39417. return true;
  39418. }
  39419. if (this._lightmapTexture === texture) {
  39420. return true;
  39421. }
  39422. if (this._refractionTexture === texture) {
  39423. return true;
  39424. }
  39425. return false;
  39426. };
  39427. PBRMaterial.prototype.clone = function (name) {
  39428. var _this = this;
  39429. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39430. clone.id = name;
  39431. clone.name = name;
  39432. return clone;
  39433. };
  39434. PBRMaterial.prototype.serialize = function () {
  39435. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39436. serializationObject.customType = "BABYLON.PBRMaterial";
  39437. return serializationObject;
  39438. };
  39439. // Statics
  39440. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39441. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39442. };
  39443. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39444. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39445. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39446. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39447. __decorate([
  39448. BABYLON.serialize(),
  39449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39450. ], PBRMaterial.prototype, "directIntensity", void 0);
  39451. __decorate([
  39452. BABYLON.serialize(),
  39453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39454. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39455. __decorate([
  39456. BABYLON.serialize(),
  39457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39458. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39459. __decorate([
  39460. BABYLON.serialize(),
  39461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39462. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39463. __decorate([
  39464. BABYLON.serialize(),
  39465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39466. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39467. __decorate([
  39468. BABYLON.serializeAsTexture(),
  39469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39470. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39471. __decorate([
  39472. BABYLON.serializeAsTexture(),
  39473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39474. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39475. __decorate([
  39476. BABYLON.serialize(),
  39477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39478. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39479. __decorate([
  39480. BABYLON.serializeAsTexture(),
  39481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39482. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39483. __decorate([
  39484. BABYLON.serializeAsTexture(),
  39485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39486. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39487. __decorate([
  39488. BABYLON.serializeAsTexture(),
  39489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39490. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39491. __decorate([
  39492. BABYLON.serializeAsTexture(),
  39493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39494. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39495. __decorate([
  39496. BABYLON.serializeAsTexture(),
  39497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39498. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39499. __decorate([
  39500. BABYLON.serialize(),
  39501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39502. ], PBRMaterial.prototype, "metallic", void 0);
  39503. __decorate([
  39504. BABYLON.serialize(),
  39505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39506. ], PBRMaterial.prototype, "roughness", void 0);
  39507. __decorate([
  39508. BABYLON.serializeAsTexture(),
  39509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39510. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39511. __decorate([
  39512. BABYLON.serializeAsTexture(),
  39513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39514. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39515. __decorate([
  39516. BABYLON.serializeAsTexture(),
  39517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39518. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39519. __decorate([
  39520. BABYLON.serializeAsTexture(),
  39521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39522. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39523. __decorate([
  39524. BABYLON.serializeAsColor3("ambient"),
  39525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39526. ], PBRMaterial.prototype, "ambientColor", void 0);
  39527. __decorate([
  39528. BABYLON.serializeAsColor3("albedo"),
  39529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39530. ], PBRMaterial.prototype, "albedoColor", void 0);
  39531. __decorate([
  39532. BABYLON.serializeAsColor3("reflectivity"),
  39533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39534. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39535. __decorate([
  39536. BABYLON.serializeAsColor3("reflection"),
  39537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39538. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39539. __decorate([
  39540. BABYLON.serializeAsColor3("emissive"),
  39541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39542. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39543. __decorate([
  39544. BABYLON.serialize(),
  39545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39546. ], PBRMaterial.prototype, "microSurface", void 0);
  39547. __decorate([
  39548. BABYLON.serialize(),
  39549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39550. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39551. __decorate([
  39552. BABYLON.serialize(),
  39553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39554. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39555. __decorate([
  39556. BABYLON.serialize(),
  39557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39558. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39559. __decorate([
  39560. BABYLON.serialize(),
  39561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39562. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39563. __decorate([
  39564. BABYLON.serialize(),
  39565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39566. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39567. __decorate([
  39568. BABYLON.serialize(),
  39569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39570. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39571. __decorate([
  39572. BABYLON.serialize(),
  39573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39574. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39575. __decorate([
  39576. BABYLON.serialize(),
  39577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39578. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39579. __decorate([
  39580. BABYLON.serialize(),
  39581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39582. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39583. __decorate([
  39584. BABYLON.serialize(),
  39585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39586. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39587. __decorate([
  39588. BABYLON.serialize(),
  39589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39590. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39591. __decorate([
  39592. BABYLON.serialize(),
  39593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39594. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39595. __decorate([
  39596. BABYLON.serialize(),
  39597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39598. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39599. __decorate([
  39600. BABYLON.serialize(),
  39601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39602. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39603. __decorate([
  39604. BABYLON.serialize(),
  39605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39606. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39607. __decorate([
  39608. BABYLON.serialize(),
  39609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39610. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39611. __decorate([
  39612. BABYLON.serialize(),
  39613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39614. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39615. __decorate([
  39616. BABYLON.serialize(),
  39617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39618. ], PBRMaterial.prototype, "useParallax", void 0);
  39619. __decorate([
  39620. BABYLON.serialize(),
  39621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39622. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39623. __decorate([
  39624. BABYLON.serialize(),
  39625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39626. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39627. __decorate([
  39628. BABYLON.serialize(),
  39629. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39630. ], PBRMaterial.prototype, "disableLighting", void 0);
  39631. __decorate([
  39632. BABYLON.serialize(),
  39633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39634. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  39635. __decorate([
  39636. BABYLON.serialize(),
  39637. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39638. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39639. __decorate([
  39640. BABYLON.serialize(),
  39641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39642. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39643. __decorate([
  39644. BABYLON.serialize(),
  39645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39646. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39647. __decorate([
  39648. BABYLON.serialize(),
  39649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39650. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39651. __decorate([
  39652. BABYLON.serialize(),
  39653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39654. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  39655. __decorate([
  39656. BABYLON.serialize(),
  39657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39658. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  39659. __decorate([
  39660. BABYLON.serializeAsTexture(),
  39661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39662. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  39663. __decorate([
  39664. BABYLON.serialize(),
  39665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39666. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  39667. __decorate([
  39668. BABYLON.serialize(),
  39669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39670. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  39671. __decorate([
  39672. BABYLON.serialize(),
  39673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39674. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  39675. return PBRMaterial;
  39676. }(BABYLON.PBRBaseMaterial));
  39677. BABYLON.PBRMaterial = PBRMaterial;
  39678. })(BABYLON || (BABYLON = {}));
  39679. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39680. var BABYLON;
  39681. (function (BABYLON) {
  39682. /**
  39683. * The PBR material of BJS following the metal roughness convention.
  39684. *
  39685. * This fits to the PBR convention in the GLTF definition:
  39686. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39687. */
  39688. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  39689. __extends(PBRMetallicRoughnessMaterial, _super);
  39690. /**
  39691. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39692. *
  39693. * @param name The material name
  39694. * @param scene The scene the material will be use in.
  39695. */
  39696. function PBRMetallicRoughnessMaterial(name, scene) {
  39697. var _this = _super.call(this, name, scene) || this;
  39698. _this._useRoughnessFromMetallicTextureAlpha = false;
  39699. _this._useRoughnessFromMetallicTextureGreen = true;
  39700. _this._useMetallnessFromMetallicTextureBlue = true;
  39701. _this._forceMetallicWorkflow = true;
  39702. return _this;
  39703. }
  39704. /**
  39705. * Return the currrent class name of the material.
  39706. */
  39707. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39708. return "PBRMetallicRoughnessMaterial";
  39709. };
  39710. /**
  39711. * Return the active textures of the material.
  39712. */
  39713. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39714. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39715. if (this.baseTexture) {
  39716. activeTextures.push(this.baseTexture);
  39717. }
  39718. if (this.metallicRoughnessTexture) {
  39719. activeTextures.push(this.metallicRoughnessTexture);
  39720. }
  39721. return activeTextures;
  39722. };
  39723. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39724. if (_super.prototype.hasTexture.call(this, texture)) {
  39725. return true;
  39726. }
  39727. if (this.baseTexture === texture) {
  39728. return true;
  39729. }
  39730. if (this.metallicRoughnessTexture === texture) {
  39731. return true;
  39732. }
  39733. return false;
  39734. };
  39735. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39736. var _this = this;
  39737. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39738. clone.id = name;
  39739. clone.name = name;
  39740. return clone;
  39741. };
  39742. /**
  39743. * Serialize the material to a parsable JSON object.
  39744. */
  39745. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39746. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39747. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39748. return serializationObject;
  39749. };
  39750. /**
  39751. * Parses a JSON object correponding to the serialize function.
  39752. */
  39753. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39754. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39755. };
  39756. __decorate([
  39757. BABYLON.serializeAsColor3(),
  39758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39759. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39760. __decorate([
  39761. BABYLON.serializeAsTexture(),
  39762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39763. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39764. __decorate([
  39765. BABYLON.serialize(),
  39766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39767. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39768. __decorate([
  39769. BABYLON.serialize(),
  39770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39771. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39772. __decorate([
  39773. BABYLON.serializeAsTexture(),
  39774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39775. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39776. return PBRMetallicRoughnessMaterial;
  39777. }(BABYLON.PBRBaseSimpleMaterial));
  39778. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39779. })(BABYLON || (BABYLON = {}));
  39780. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39781. var BABYLON;
  39782. (function (BABYLON) {
  39783. /**
  39784. * The PBR material of BJS following the specular glossiness convention.
  39785. *
  39786. * This fits to the PBR convention in the GLTF definition:
  39787. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39788. */
  39789. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  39790. __extends(PBRSpecularGlossinessMaterial, _super);
  39791. /**
  39792. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39793. *
  39794. * @param name The material name
  39795. * @param scene The scene the material will be use in.
  39796. */
  39797. function PBRSpecularGlossinessMaterial(name, scene) {
  39798. var _this = _super.call(this, name, scene) || this;
  39799. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39800. return _this;
  39801. }
  39802. /**
  39803. * Return the currrent class name of the material.
  39804. */
  39805. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39806. return "PBRSpecularGlossinessMaterial";
  39807. };
  39808. /**
  39809. * Return the active textures of the material.
  39810. */
  39811. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39812. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39813. if (this.diffuseTexture) {
  39814. activeTextures.push(this.diffuseTexture);
  39815. }
  39816. if (this.specularGlossinessTexture) {
  39817. activeTextures.push(this.specularGlossinessTexture);
  39818. }
  39819. return activeTextures;
  39820. };
  39821. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39822. if (_super.prototype.hasTexture.call(this, texture)) {
  39823. return true;
  39824. }
  39825. if (this.diffuseTexture === texture) {
  39826. return true;
  39827. }
  39828. if (this.specularGlossinessTexture === texture) {
  39829. return true;
  39830. }
  39831. return false;
  39832. };
  39833. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39834. var _this = this;
  39835. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39836. clone.id = name;
  39837. clone.name = name;
  39838. return clone;
  39839. };
  39840. /**
  39841. * Serialize the material to a parsable JSON object.
  39842. */
  39843. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39844. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39845. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39846. return serializationObject;
  39847. };
  39848. /**
  39849. * Parses a JSON object correponding to the serialize function.
  39850. */
  39851. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39852. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39853. };
  39854. __decorate([
  39855. BABYLON.serializeAsColor3("diffuse"),
  39856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39857. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39858. __decorate([
  39859. BABYLON.serializeAsTexture(),
  39860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39861. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39862. __decorate([
  39863. BABYLON.serializeAsColor3("specular"),
  39864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39865. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39866. __decorate([
  39867. BABYLON.serialize(),
  39868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39869. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39870. __decorate([
  39871. BABYLON.serializeAsTexture(),
  39872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39873. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39874. return PBRSpecularGlossinessMaterial;
  39875. }(BABYLON.PBRBaseSimpleMaterial));
  39876. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39877. })(BABYLON || (BABYLON = {}));
  39878. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39879. var BABYLON;
  39880. (function (BABYLON) {
  39881. BABYLON.CameraInputTypes = {};
  39882. var CameraInputsManager = /** @class */ (function () {
  39883. function CameraInputsManager(camera) {
  39884. this.attached = {};
  39885. this.camera = camera;
  39886. this.checkInputs = function () { };
  39887. }
  39888. /**
  39889. * Add an input method to a camera.
  39890. * builtin inputs example: camera.inputs.addGamepad();
  39891. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  39892. * @param input camera input method
  39893. */
  39894. CameraInputsManager.prototype.add = function (input) {
  39895. var type = input.getSimpleName();
  39896. if (this.attached[type]) {
  39897. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  39898. return;
  39899. }
  39900. this.attached[type] = input;
  39901. input.camera = this.camera;
  39902. //for checkInputs, we are dynamically creating a function
  39903. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  39904. if (input.checkInputs) {
  39905. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39906. }
  39907. if (this.attachedElement) {
  39908. input.attachControl(this.attachedElement);
  39909. }
  39910. };
  39911. /**
  39912. * Remove a specific input method from a camera
  39913. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  39914. * @param inputToRemove camera input method
  39915. */
  39916. CameraInputsManager.prototype.remove = function (inputToRemove) {
  39917. for (var cam in this.attached) {
  39918. var input = this.attached[cam];
  39919. if (input === inputToRemove) {
  39920. input.detachControl(this.attachedElement);
  39921. input.camera = null;
  39922. delete this.attached[cam];
  39923. this.rebuildInputCheck();
  39924. }
  39925. }
  39926. };
  39927. CameraInputsManager.prototype.removeByType = function (inputType) {
  39928. for (var cam in this.attached) {
  39929. var input = this.attached[cam];
  39930. if (input.getClassName() === inputType) {
  39931. input.detachControl(this.attachedElement);
  39932. input.camera = null;
  39933. delete this.attached[cam];
  39934. this.rebuildInputCheck();
  39935. }
  39936. }
  39937. };
  39938. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  39939. var current = this.checkInputs;
  39940. return function () {
  39941. current();
  39942. fn();
  39943. };
  39944. };
  39945. CameraInputsManager.prototype.attachInput = function (input) {
  39946. if (this.attachedElement) {
  39947. input.attachControl(this.attachedElement, this.noPreventDefault);
  39948. }
  39949. };
  39950. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  39951. if (noPreventDefault === void 0) { noPreventDefault = false; }
  39952. if (this.attachedElement) {
  39953. return;
  39954. }
  39955. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  39956. this.attachedElement = element;
  39957. this.noPreventDefault = noPreventDefault;
  39958. for (var cam in this.attached) {
  39959. this.attached[cam].attachControl(element, noPreventDefault);
  39960. }
  39961. };
  39962. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  39963. if (disconnect === void 0) { disconnect = false; }
  39964. if (this.attachedElement !== element) {
  39965. return;
  39966. }
  39967. for (var cam in this.attached) {
  39968. this.attached[cam].detachControl(element);
  39969. if (disconnect) {
  39970. this.attached[cam].camera = null;
  39971. }
  39972. }
  39973. this.attachedElement = null;
  39974. };
  39975. CameraInputsManager.prototype.rebuildInputCheck = function () {
  39976. this.checkInputs = function () { };
  39977. for (var cam in this.attached) {
  39978. var input = this.attached[cam];
  39979. if (input.checkInputs) {
  39980. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39981. }
  39982. }
  39983. };
  39984. /**
  39985. * Remove all attached input methods from a camera
  39986. */
  39987. CameraInputsManager.prototype.clear = function () {
  39988. if (this.attachedElement) {
  39989. this.detachElement(this.attachedElement, true);
  39990. }
  39991. this.attached = {};
  39992. this.attachedElement = null;
  39993. this.checkInputs = function () { };
  39994. };
  39995. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  39996. var inputs = {};
  39997. for (var cam in this.attached) {
  39998. var input = this.attached[cam];
  39999. var res = BABYLON.SerializationHelper.Serialize(input);
  40000. inputs[input.getClassName()] = res;
  40001. }
  40002. serializedCamera.inputsmgr = inputs;
  40003. };
  40004. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40005. var parsedInputs = parsedCamera.inputsmgr;
  40006. if (parsedInputs) {
  40007. this.clear();
  40008. for (var n in parsedInputs) {
  40009. var construct = BABYLON.CameraInputTypes[n];
  40010. if (construct) {
  40011. var parsedinput = parsedInputs[n];
  40012. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40013. this.add(input);
  40014. }
  40015. }
  40016. }
  40017. else {
  40018. //2016-03-08 this part is for managing backward compatibility
  40019. for (var n in this.attached) {
  40020. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40021. if (construct) {
  40022. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40023. this.remove(this.attached[n]);
  40024. this.add(input);
  40025. }
  40026. }
  40027. }
  40028. };
  40029. return CameraInputsManager;
  40030. }());
  40031. BABYLON.CameraInputsManager = CameraInputsManager;
  40032. })(BABYLON || (BABYLON = {}));
  40033. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40034. var BABYLON;
  40035. (function (BABYLON) {
  40036. var TargetCamera = /** @class */ (function (_super) {
  40037. __extends(TargetCamera, _super);
  40038. function TargetCamera(name, position, scene) {
  40039. var _this = _super.call(this, name, position, scene) || this;
  40040. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40041. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40042. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40043. _this.speed = 2.0;
  40044. _this.noRotationConstraint = false;
  40045. _this.lockedTarget = null;
  40046. _this._currentTarget = BABYLON.Vector3.Zero();
  40047. _this._viewMatrix = BABYLON.Matrix.Zero();
  40048. _this._camMatrix = BABYLON.Matrix.Zero();
  40049. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40050. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40051. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40052. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40053. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40054. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40055. _this._tempMatrix = BABYLON.Matrix.Zero();
  40056. return _this;
  40057. }
  40058. TargetCamera.prototype.getFrontPosition = function (distance) {
  40059. this.getWorldMatrix();
  40060. var direction = this.getTarget().subtract(this.position);
  40061. direction.normalize();
  40062. direction.scaleInPlace(distance);
  40063. return this.globalPosition.add(direction);
  40064. };
  40065. TargetCamera.prototype._getLockedTargetPosition = function () {
  40066. if (!this.lockedTarget) {
  40067. return null;
  40068. }
  40069. if (this.lockedTarget.absolutePosition) {
  40070. this.lockedTarget.computeWorldMatrix();
  40071. }
  40072. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40073. };
  40074. TargetCamera.prototype.storeState = function () {
  40075. this._storedPosition = this.position.clone();
  40076. this._storedRotation = this.rotation.clone();
  40077. if (this.rotationQuaternion) {
  40078. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40079. }
  40080. return _super.prototype.storeState.call(this);
  40081. };
  40082. /**
  40083. * Restored camera state. You must call storeState() first
  40084. */
  40085. TargetCamera.prototype._restoreStateValues = function () {
  40086. if (!_super.prototype._restoreStateValues.call(this)) {
  40087. return false;
  40088. }
  40089. this.position = this._storedPosition.clone();
  40090. this.rotation = this._storedRotation.clone();
  40091. if (this.rotationQuaternion) {
  40092. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40093. }
  40094. this.cameraDirection.copyFromFloats(0, 0, 0);
  40095. this.cameraRotation.copyFromFloats(0, 0);
  40096. return true;
  40097. };
  40098. // Cache
  40099. TargetCamera.prototype._initCache = function () {
  40100. _super.prototype._initCache.call(this);
  40101. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40102. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40103. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40104. };
  40105. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40106. if (!ignoreParentClass) {
  40107. _super.prototype._updateCache.call(this);
  40108. }
  40109. var lockedTargetPosition = this._getLockedTargetPosition();
  40110. if (!lockedTargetPosition) {
  40111. this._cache.lockedTarget = null;
  40112. }
  40113. else {
  40114. if (!this._cache.lockedTarget) {
  40115. this._cache.lockedTarget = lockedTargetPosition.clone();
  40116. }
  40117. else {
  40118. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40119. }
  40120. }
  40121. this._cache.rotation.copyFrom(this.rotation);
  40122. if (this.rotationQuaternion)
  40123. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40124. };
  40125. // Synchronized
  40126. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40127. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40128. return false;
  40129. }
  40130. var lockedTargetPosition = this._getLockedTargetPosition();
  40131. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40132. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40133. };
  40134. // Methods
  40135. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40136. var engine = this.getEngine();
  40137. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40138. };
  40139. // Target
  40140. TargetCamera.prototype.setTarget = function (target) {
  40141. this.upVector.normalize();
  40142. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40143. this._camMatrix.invert();
  40144. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40145. var vDir = target.subtract(this.position);
  40146. if (vDir.x >= 0.0) {
  40147. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40148. }
  40149. else {
  40150. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40151. }
  40152. this.rotation.z = 0;
  40153. if (isNaN(this.rotation.x)) {
  40154. this.rotation.x = 0;
  40155. }
  40156. if (isNaN(this.rotation.y)) {
  40157. this.rotation.y = 0;
  40158. }
  40159. if (isNaN(this.rotation.z)) {
  40160. this.rotation.z = 0;
  40161. }
  40162. if (this.rotationQuaternion) {
  40163. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40164. }
  40165. };
  40166. /**
  40167. * Return the current target position of the camera. This value is expressed in local space.
  40168. */
  40169. TargetCamera.prototype.getTarget = function () {
  40170. return this._currentTarget;
  40171. };
  40172. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40173. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40174. };
  40175. TargetCamera.prototype._updatePosition = function () {
  40176. if (this.parent) {
  40177. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40178. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40179. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40180. return;
  40181. }
  40182. this.position.addInPlace(this.cameraDirection);
  40183. };
  40184. TargetCamera.prototype._checkInputs = function () {
  40185. var needToMove = this._decideIfNeedsToMove();
  40186. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40187. // Move
  40188. if (needToMove) {
  40189. this._updatePosition();
  40190. }
  40191. // Rotate
  40192. if (needToRotate) {
  40193. this.rotation.x += this.cameraRotation.x;
  40194. this.rotation.y += this.cameraRotation.y;
  40195. //rotate, if quaternion is set and rotation was used
  40196. if (this.rotationQuaternion) {
  40197. var len = this.rotation.lengthSquared();
  40198. if (len) {
  40199. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40200. }
  40201. }
  40202. if (!this.noRotationConstraint) {
  40203. var limit = (Math.PI / 2) * 0.95;
  40204. if (this.rotation.x > limit)
  40205. this.rotation.x = limit;
  40206. if (this.rotation.x < -limit)
  40207. this.rotation.x = -limit;
  40208. }
  40209. }
  40210. // Inertia
  40211. if (needToMove) {
  40212. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40213. this.cameraDirection.x = 0;
  40214. }
  40215. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40216. this.cameraDirection.y = 0;
  40217. }
  40218. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40219. this.cameraDirection.z = 0;
  40220. }
  40221. this.cameraDirection.scaleInPlace(this.inertia);
  40222. }
  40223. if (needToRotate) {
  40224. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40225. this.cameraRotation.x = 0;
  40226. }
  40227. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40228. this.cameraRotation.y = 0;
  40229. }
  40230. this.cameraRotation.scaleInPlace(this.inertia);
  40231. }
  40232. _super.prototype._checkInputs.call(this);
  40233. };
  40234. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40235. if (this.rotationQuaternion) {
  40236. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40237. }
  40238. else {
  40239. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40240. }
  40241. //update the up vector!
  40242. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40243. };
  40244. TargetCamera.prototype._getViewMatrix = function () {
  40245. if (this.lockedTarget) {
  40246. this.setTarget(this._getLockedTargetPosition());
  40247. }
  40248. // Compute
  40249. this._updateCameraRotationMatrix();
  40250. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40251. // Computing target and final matrix
  40252. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40253. if (this.getScene().useRightHandedSystem) {
  40254. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40255. }
  40256. else {
  40257. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40258. }
  40259. return this._viewMatrix;
  40260. };
  40261. /**
  40262. * @override
  40263. * Override Camera.createRigCamera
  40264. */
  40265. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40266. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40267. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40268. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40269. if (!this.rotationQuaternion) {
  40270. this.rotationQuaternion = new BABYLON.Quaternion();
  40271. }
  40272. rigCamera._cameraRigParams = {};
  40273. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40274. }
  40275. return rigCamera;
  40276. }
  40277. return null;
  40278. };
  40279. /**
  40280. * @override
  40281. * Override Camera._updateRigCameras
  40282. */
  40283. TargetCamera.prototype._updateRigCameras = function () {
  40284. var camLeft = this._rigCameras[0];
  40285. var camRight = this._rigCameras[1];
  40286. switch (this.cameraRigMode) {
  40287. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40288. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40289. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40290. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40291. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40292. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40293. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40294. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40295. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40296. camLeft.setTarget(this.getTarget());
  40297. camRight.setTarget(this.getTarget());
  40298. break;
  40299. case BABYLON.Camera.RIG_MODE_VR:
  40300. if (camLeft.rotationQuaternion) {
  40301. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40302. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40303. }
  40304. else {
  40305. camLeft.rotation.copyFrom(this.rotation);
  40306. camRight.rotation.copyFrom(this.rotation);
  40307. }
  40308. camLeft.position.copyFrom(this.position);
  40309. camRight.position.copyFrom(this.position);
  40310. break;
  40311. }
  40312. _super.prototype._updateRigCameras.call(this);
  40313. };
  40314. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40315. if (!this._rigCamTransformMatrix) {
  40316. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40317. }
  40318. var target = this.getTarget();
  40319. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40320. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40321. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40322. };
  40323. TargetCamera.prototype.getClassName = function () {
  40324. return "TargetCamera";
  40325. };
  40326. __decorate([
  40327. BABYLON.serializeAsVector3()
  40328. ], TargetCamera.prototype, "rotation", void 0);
  40329. __decorate([
  40330. BABYLON.serialize()
  40331. ], TargetCamera.prototype, "speed", void 0);
  40332. __decorate([
  40333. BABYLON.serializeAsMeshReference("lockedTargetId")
  40334. ], TargetCamera.prototype, "lockedTarget", void 0);
  40335. return TargetCamera;
  40336. }(BABYLON.Camera));
  40337. BABYLON.TargetCamera = TargetCamera;
  40338. })(BABYLON || (BABYLON = {}));
  40339. //# sourceMappingURL=babylon.targetCamera.js.map
  40340. var BABYLON;
  40341. (function (BABYLON) {
  40342. var FreeCameraMouseInput = /** @class */ (function () {
  40343. function FreeCameraMouseInput(touchEnabled) {
  40344. if (touchEnabled === void 0) { touchEnabled = true; }
  40345. this.touchEnabled = touchEnabled;
  40346. this.buttons = [0, 1, 2];
  40347. this.angularSensibility = 2000.0;
  40348. this.previousPosition = null;
  40349. }
  40350. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40351. var _this = this;
  40352. var engine = this.camera.getEngine();
  40353. if (!this._pointerInput) {
  40354. this._pointerInput = function (p, s) {
  40355. var evt = p.event;
  40356. if (engine.isInVRExclusivePointerMode) {
  40357. return;
  40358. }
  40359. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40360. return;
  40361. }
  40362. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40363. return;
  40364. }
  40365. var srcElement = (evt.srcElement || evt.target);
  40366. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40367. try {
  40368. srcElement.setPointerCapture(evt.pointerId);
  40369. }
  40370. catch (e) {
  40371. //Nothing to do with the error. Execution will continue.
  40372. }
  40373. _this.previousPosition = {
  40374. x: evt.clientX,
  40375. y: evt.clientY
  40376. };
  40377. if (!noPreventDefault) {
  40378. evt.preventDefault();
  40379. element.focus();
  40380. }
  40381. }
  40382. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40383. try {
  40384. srcElement.releasePointerCapture(evt.pointerId);
  40385. }
  40386. catch (e) {
  40387. //Nothing to do with the error.
  40388. }
  40389. _this.previousPosition = null;
  40390. if (!noPreventDefault) {
  40391. evt.preventDefault();
  40392. }
  40393. }
  40394. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40395. if (!_this.previousPosition || engine.isPointerLock) {
  40396. return;
  40397. }
  40398. var offsetX = evt.clientX - _this.previousPosition.x;
  40399. var offsetY = evt.clientY - _this.previousPosition.y;
  40400. if (_this.camera.getScene().useRightHandedSystem) {
  40401. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40402. }
  40403. else {
  40404. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40405. }
  40406. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40407. _this.previousPosition = {
  40408. x: evt.clientX,
  40409. y: evt.clientY
  40410. };
  40411. if (!noPreventDefault) {
  40412. evt.preventDefault();
  40413. }
  40414. }
  40415. };
  40416. }
  40417. this._onMouseMove = function (evt) {
  40418. if (!engine.isPointerLock) {
  40419. return;
  40420. }
  40421. if (engine.isInVRExclusivePointerMode) {
  40422. return;
  40423. }
  40424. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40425. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40426. if (_this.camera.getScene().useRightHandedSystem) {
  40427. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40428. }
  40429. else {
  40430. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40431. }
  40432. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40433. _this.previousPosition = null;
  40434. if (!noPreventDefault) {
  40435. evt.preventDefault();
  40436. }
  40437. };
  40438. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40439. element.addEventListener("mousemove", this._onMouseMove, false);
  40440. };
  40441. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40442. if (this._observer && element) {
  40443. this.camera.getScene().onPointerObservable.remove(this._observer);
  40444. if (this._onMouseMove) {
  40445. element.removeEventListener("mousemove", this._onMouseMove);
  40446. }
  40447. this._observer = null;
  40448. this._onMouseMove = null;
  40449. this.previousPosition = null;
  40450. }
  40451. };
  40452. FreeCameraMouseInput.prototype.getClassName = function () {
  40453. return "FreeCameraMouseInput";
  40454. };
  40455. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40456. return "mouse";
  40457. };
  40458. __decorate([
  40459. BABYLON.serialize()
  40460. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40461. __decorate([
  40462. BABYLON.serialize()
  40463. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40464. return FreeCameraMouseInput;
  40465. }());
  40466. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40467. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40468. })(BABYLON || (BABYLON = {}));
  40469. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40470. var BABYLON;
  40471. (function (BABYLON) {
  40472. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40473. function FreeCameraKeyboardMoveInput() {
  40474. this._keys = new Array();
  40475. this.keysUp = [38];
  40476. this.keysDown = [40];
  40477. this.keysLeft = [37];
  40478. this.keysRight = [39];
  40479. }
  40480. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40481. var _this = this;
  40482. if (this._onCanvasBlurObserver) {
  40483. return;
  40484. }
  40485. this._scene = this.camera.getScene();
  40486. this._engine = this._scene.getEngine();
  40487. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40488. _this._keys = [];
  40489. });
  40490. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40491. var evt = info.event;
  40492. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40493. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40494. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40495. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40496. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40497. var index = _this._keys.indexOf(evt.keyCode);
  40498. if (index === -1) {
  40499. _this._keys.push(evt.keyCode);
  40500. }
  40501. if (!noPreventDefault) {
  40502. evt.preventDefault();
  40503. }
  40504. }
  40505. }
  40506. else {
  40507. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40508. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40509. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40510. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40511. var index = _this._keys.indexOf(evt.keyCode);
  40512. if (index >= 0) {
  40513. _this._keys.splice(index, 1);
  40514. }
  40515. if (!noPreventDefault) {
  40516. evt.preventDefault();
  40517. }
  40518. }
  40519. }
  40520. });
  40521. };
  40522. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40523. if (this._scene) {
  40524. if (this._onKeyboardObserver) {
  40525. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40526. }
  40527. if (this._onCanvasBlurObserver) {
  40528. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40529. }
  40530. this._onKeyboardObserver = null;
  40531. this._onCanvasBlurObserver = null;
  40532. }
  40533. this._keys = [];
  40534. };
  40535. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40536. if (this._onKeyboardObserver) {
  40537. var camera = this.camera;
  40538. // Keyboard
  40539. for (var index = 0; index < this._keys.length; index++) {
  40540. var keyCode = this._keys[index];
  40541. var speed = camera._computeLocalCameraSpeed();
  40542. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40543. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40544. }
  40545. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40546. camera._localDirection.copyFromFloats(0, 0, speed);
  40547. }
  40548. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40549. camera._localDirection.copyFromFloats(speed, 0, 0);
  40550. }
  40551. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40552. camera._localDirection.copyFromFloats(0, 0, -speed);
  40553. }
  40554. if (camera.getScene().useRightHandedSystem) {
  40555. camera._localDirection.z *= -1;
  40556. }
  40557. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40558. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40559. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40560. }
  40561. }
  40562. };
  40563. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40564. return "FreeCameraKeyboardMoveInput";
  40565. };
  40566. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40567. this._keys = [];
  40568. };
  40569. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40570. return "keyboard";
  40571. };
  40572. __decorate([
  40573. BABYLON.serialize()
  40574. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40575. __decorate([
  40576. BABYLON.serialize()
  40577. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40578. __decorate([
  40579. BABYLON.serialize()
  40580. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40581. __decorate([
  40582. BABYLON.serialize()
  40583. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40584. return FreeCameraKeyboardMoveInput;
  40585. }());
  40586. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40587. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40588. })(BABYLON || (BABYLON = {}));
  40589. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40590. var BABYLON;
  40591. (function (BABYLON) {
  40592. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40593. __extends(FreeCameraInputsManager, _super);
  40594. function FreeCameraInputsManager(camera) {
  40595. return _super.call(this, camera) || this;
  40596. }
  40597. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40598. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40599. return this;
  40600. };
  40601. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40602. if (touchEnabled === void 0) { touchEnabled = true; }
  40603. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40604. return this;
  40605. };
  40606. FreeCameraInputsManager.prototype.addGamepad = function () {
  40607. this.add(new BABYLON.FreeCameraGamepadInput());
  40608. return this;
  40609. };
  40610. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40611. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40612. return this;
  40613. };
  40614. FreeCameraInputsManager.prototype.addTouch = function () {
  40615. this.add(new BABYLON.FreeCameraTouchInput());
  40616. return this;
  40617. };
  40618. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40619. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40620. return this;
  40621. };
  40622. return FreeCameraInputsManager;
  40623. }(BABYLON.CameraInputsManager));
  40624. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40625. })(BABYLON || (BABYLON = {}));
  40626. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40627. var BABYLON;
  40628. (function (BABYLON) {
  40629. var FreeCamera = /** @class */ (function (_super) {
  40630. __extends(FreeCamera, _super);
  40631. function FreeCamera(name, position, scene) {
  40632. var _this = _super.call(this, name, position, scene) || this;
  40633. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  40634. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  40635. _this.checkCollisions = false;
  40636. _this.applyGravity = false;
  40637. _this._needMoveForGravity = false;
  40638. _this._oldPosition = BABYLON.Vector3.Zero();
  40639. _this._diffPosition = BABYLON.Vector3.Zero();
  40640. _this._newPosition = BABYLON.Vector3.Zero();
  40641. // Collisions
  40642. _this._collisionMask = -1;
  40643. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40644. if (collidedMesh === void 0) { collidedMesh = null; }
  40645. //TODO move this to the collision coordinator!
  40646. if (_this.getScene().workerCollisions)
  40647. newPosition.multiplyInPlace(_this._collider._radius);
  40648. var updatePosition = function (newPos) {
  40649. _this._newPosition.copyFrom(newPos);
  40650. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  40651. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  40652. _this.position.addInPlace(_this._diffPosition);
  40653. if (_this.onCollide && collidedMesh) {
  40654. _this.onCollide(collidedMesh);
  40655. }
  40656. }
  40657. };
  40658. updatePosition(newPosition);
  40659. };
  40660. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  40661. _this.inputs.addKeyboard().addMouse();
  40662. return _this;
  40663. }
  40664. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  40665. //-- begin properties for backward compatibility for inputs
  40666. /**
  40667. * Gets the input sensibility for a mouse input. (default is 2000.0)
  40668. * Higher values reduce sensitivity.
  40669. */
  40670. get: function () {
  40671. var mouse = this.inputs.attached["mouse"];
  40672. if (mouse)
  40673. return mouse.angularSensibility;
  40674. return 0;
  40675. },
  40676. /**
  40677. * Sets the input sensibility for a mouse input. (default is 2000.0)
  40678. * Higher values reduce sensitivity.
  40679. */
  40680. set: function (value) {
  40681. var mouse = this.inputs.attached["mouse"];
  40682. if (mouse)
  40683. mouse.angularSensibility = value;
  40684. },
  40685. enumerable: true,
  40686. configurable: true
  40687. });
  40688. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  40689. get: function () {
  40690. var keyboard = this.inputs.attached["keyboard"];
  40691. if (keyboard)
  40692. return keyboard.keysUp;
  40693. return [];
  40694. },
  40695. set: function (value) {
  40696. var keyboard = this.inputs.attached["keyboard"];
  40697. if (keyboard)
  40698. keyboard.keysUp = value;
  40699. },
  40700. enumerable: true,
  40701. configurable: true
  40702. });
  40703. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  40704. get: function () {
  40705. var keyboard = this.inputs.attached["keyboard"];
  40706. if (keyboard)
  40707. return keyboard.keysDown;
  40708. return [];
  40709. },
  40710. set: function (value) {
  40711. var keyboard = this.inputs.attached["keyboard"];
  40712. if (keyboard)
  40713. keyboard.keysDown = value;
  40714. },
  40715. enumerable: true,
  40716. configurable: true
  40717. });
  40718. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  40719. get: function () {
  40720. var keyboard = this.inputs.attached["keyboard"];
  40721. if (keyboard)
  40722. return keyboard.keysLeft;
  40723. return [];
  40724. },
  40725. set: function (value) {
  40726. var keyboard = this.inputs.attached["keyboard"];
  40727. if (keyboard)
  40728. keyboard.keysLeft = value;
  40729. },
  40730. enumerable: true,
  40731. configurable: true
  40732. });
  40733. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  40734. get: function () {
  40735. var keyboard = this.inputs.attached["keyboard"];
  40736. if (keyboard)
  40737. return keyboard.keysRight;
  40738. return [];
  40739. },
  40740. set: function (value) {
  40741. var keyboard = this.inputs.attached["keyboard"];
  40742. if (keyboard)
  40743. keyboard.keysRight = value;
  40744. },
  40745. enumerable: true,
  40746. configurable: true
  40747. });
  40748. // Controls
  40749. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  40750. this.inputs.attachElement(element, noPreventDefault);
  40751. };
  40752. FreeCamera.prototype.detachControl = function (element) {
  40753. this.inputs.detachElement(element);
  40754. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40755. this.cameraRotation = new BABYLON.Vector2(0, 0);
  40756. };
  40757. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  40758. get: function () {
  40759. return this._collisionMask;
  40760. },
  40761. set: function (mask) {
  40762. this._collisionMask = !isNaN(mask) ? mask : -1;
  40763. },
  40764. enumerable: true,
  40765. configurable: true
  40766. });
  40767. FreeCamera.prototype._collideWithWorld = function (displacement) {
  40768. var globalPosition;
  40769. if (this.parent) {
  40770. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  40771. }
  40772. else {
  40773. globalPosition = this.position;
  40774. }
  40775. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  40776. this._oldPosition.addInPlace(this.ellipsoidOffset);
  40777. if (!this._collider) {
  40778. this._collider = new BABYLON.Collider();
  40779. }
  40780. this._collider._radius = this.ellipsoid;
  40781. this._collider.collisionMask = this._collisionMask;
  40782. //no need for clone, as long as gravity is not on.
  40783. var actualDisplacement = displacement;
  40784. //add gravity to the direction to prevent the dual-collision checking
  40785. if (this.applyGravity) {
  40786. //this prevents mending with cameraDirection, a global variable of the free camera class.
  40787. actualDisplacement = displacement.add(this.getScene().gravity);
  40788. }
  40789. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40790. };
  40791. FreeCamera.prototype._checkInputs = function () {
  40792. if (!this._localDirection) {
  40793. this._localDirection = BABYLON.Vector3.Zero();
  40794. this._transformedDirection = BABYLON.Vector3.Zero();
  40795. }
  40796. this.inputs.checkInputs();
  40797. _super.prototype._checkInputs.call(this);
  40798. };
  40799. FreeCamera.prototype._decideIfNeedsToMove = function () {
  40800. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40801. };
  40802. FreeCamera.prototype._updatePosition = function () {
  40803. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  40804. this._collideWithWorld(this.cameraDirection);
  40805. }
  40806. else {
  40807. _super.prototype._updatePosition.call(this);
  40808. }
  40809. };
  40810. FreeCamera.prototype.dispose = function () {
  40811. this.inputs.clear();
  40812. _super.prototype.dispose.call(this);
  40813. };
  40814. FreeCamera.prototype.getClassName = function () {
  40815. return "FreeCamera";
  40816. };
  40817. __decorate([
  40818. BABYLON.serializeAsVector3()
  40819. ], FreeCamera.prototype, "ellipsoid", void 0);
  40820. __decorate([
  40821. BABYLON.serializeAsVector3()
  40822. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  40823. __decorate([
  40824. BABYLON.serialize()
  40825. ], FreeCamera.prototype, "checkCollisions", void 0);
  40826. __decorate([
  40827. BABYLON.serialize()
  40828. ], FreeCamera.prototype, "applyGravity", void 0);
  40829. return FreeCamera;
  40830. }(BABYLON.TargetCamera));
  40831. BABYLON.FreeCamera = FreeCamera;
  40832. })(BABYLON || (BABYLON = {}));
  40833. //# sourceMappingURL=babylon.freeCamera.js.map
  40834. var BABYLON;
  40835. (function (BABYLON) {
  40836. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  40837. function ArcRotateCameraKeyboardMoveInput() {
  40838. this._keys = new Array();
  40839. this.keysUp = [38];
  40840. this.keysDown = [40];
  40841. this.keysLeft = [37];
  40842. this.keysRight = [39];
  40843. this.keysReset = [220];
  40844. this.panningSensibility = 50.0;
  40845. this.zoomingSensibility = 25.0;
  40846. this.useAltToZoom = true;
  40847. }
  40848. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40849. var _this = this;
  40850. if (this._onCanvasBlurObserver) {
  40851. return;
  40852. }
  40853. this._scene = this.camera.getScene();
  40854. this._engine = this._scene.getEngine();
  40855. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40856. _this._keys = [];
  40857. });
  40858. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40859. var evt = info.event;
  40860. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40861. _this._ctrlPressed = evt.ctrlKey;
  40862. _this._altPressed = evt.altKey;
  40863. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40864. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40865. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40866. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40867. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40868. var index = _this._keys.indexOf(evt.keyCode);
  40869. if (index === -1) {
  40870. _this._keys.push(evt.keyCode);
  40871. }
  40872. if (evt.preventDefault) {
  40873. if (!noPreventDefault) {
  40874. evt.preventDefault();
  40875. }
  40876. }
  40877. }
  40878. }
  40879. else {
  40880. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40881. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40882. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40883. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40884. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40885. var index = _this._keys.indexOf(evt.keyCode);
  40886. if (index >= 0) {
  40887. _this._keys.splice(index, 1);
  40888. }
  40889. if (evt.preventDefault) {
  40890. if (!noPreventDefault) {
  40891. evt.preventDefault();
  40892. }
  40893. }
  40894. }
  40895. }
  40896. });
  40897. };
  40898. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40899. if (this._scene) {
  40900. if (this._onKeyboardObserver) {
  40901. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40902. }
  40903. if (this._onCanvasBlurObserver) {
  40904. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40905. }
  40906. this._onKeyboardObserver = null;
  40907. this._onCanvasBlurObserver = null;
  40908. }
  40909. this._keys = [];
  40910. };
  40911. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40912. if (this._onKeyboardObserver) {
  40913. var camera = this.camera;
  40914. for (var index = 0; index < this._keys.length; index++) {
  40915. var keyCode = this._keys[index];
  40916. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40917. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40918. camera.inertialPanningX -= 1 / this.panningSensibility;
  40919. }
  40920. else {
  40921. camera.inertialAlphaOffset -= 0.01;
  40922. }
  40923. }
  40924. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40925. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40926. camera.inertialPanningY += 1 / this.panningSensibility;
  40927. }
  40928. else if (this._altPressed && this.useAltToZoom) {
  40929. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  40930. }
  40931. else {
  40932. camera.inertialBetaOffset -= 0.01;
  40933. }
  40934. }
  40935. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40936. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40937. camera.inertialPanningX += 1 / this.panningSensibility;
  40938. }
  40939. else {
  40940. camera.inertialAlphaOffset += 0.01;
  40941. }
  40942. }
  40943. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40944. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40945. camera.inertialPanningY -= 1 / this.panningSensibility;
  40946. }
  40947. else if (this._altPressed && this.useAltToZoom) {
  40948. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  40949. }
  40950. else {
  40951. camera.inertialBetaOffset += 0.01;
  40952. }
  40953. }
  40954. else if (this.keysReset.indexOf(keyCode) !== -1) {
  40955. camera.restoreState();
  40956. }
  40957. }
  40958. }
  40959. };
  40960. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  40961. return "ArcRotateCameraKeyboardMoveInput";
  40962. };
  40963. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40964. return "keyboard";
  40965. };
  40966. __decorate([
  40967. BABYLON.serialize()
  40968. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40969. __decorate([
  40970. BABYLON.serialize()
  40971. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40972. __decorate([
  40973. BABYLON.serialize()
  40974. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40975. __decorate([
  40976. BABYLON.serialize()
  40977. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40978. __decorate([
  40979. BABYLON.serialize()
  40980. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  40981. __decorate([
  40982. BABYLON.serialize()
  40983. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  40984. __decorate([
  40985. BABYLON.serialize()
  40986. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  40987. __decorate([
  40988. BABYLON.serialize()
  40989. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  40990. return ArcRotateCameraKeyboardMoveInput;
  40991. }());
  40992. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  40993. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  40994. })(BABYLON || (BABYLON = {}));
  40995. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  40996. var BABYLON;
  40997. (function (BABYLON) {
  40998. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  40999. function ArcRotateCameraMouseWheelInput() {
  41000. this.wheelPrecision = 3.0;
  41001. /**
  41002. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41003. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41004. */
  41005. this.wheelDeltaPercentage = 0;
  41006. }
  41007. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41008. var _this = this;
  41009. this._wheel = function (p, s) {
  41010. //sanity check - this should be a PointerWheel event.
  41011. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41012. return;
  41013. var event = p.event;
  41014. var delta = 0;
  41015. if (event.wheelDelta) {
  41016. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41017. }
  41018. else if (event.detail) {
  41019. delta = -event.detail / _this.wheelPrecision;
  41020. }
  41021. if (delta)
  41022. _this.camera.inertialRadiusOffset += delta;
  41023. if (event.preventDefault) {
  41024. if (!noPreventDefault) {
  41025. event.preventDefault();
  41026. }
  41027. }
  41028. };
  41029. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41030. };
  41031. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41032. if (this._observer && element) {
  41033. this.camera.getScene().onPointerObservable.remove(this._observer);
  41034. this._observer = null;
  41035. this._wheel = null;
  41036. }
  41037. };
  41038. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41039. return "ArcRotateCameraMouseWheelInput";
  41040. };
  41041. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41042. return "mousewheel";
  41043. };
  41044. __decorate([
  41045. BABYLON.serialize()
  41046. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41047. __decorate([
  41048. BABYLON.serialize()
  41049. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41050. return ArcRotateCameraMouseWheelInput;
  41051. }());
  41052. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41053. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41054. })(BABYLON || (BABYLON = {}));
  41055. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41056. var BABYLON;
  41057. (function (BABYLON) {
  41058. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41059. function ArcRotateCameraPointersInput() {
  41060. this.buttons = [0, 1, 2];
  41061. this.angularSensibilityX = 1000.0;
  41062. this.angularSensibilityY = 1000.0;
  41063. this.pinchPrecision = 12.0;
  41064. /**
  41065. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41066. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41067. */
  41068. this.pinchDeltaPercentage = 0;
  41069. this.panningSensibility = 1000.0;
  41070. this.multiTouchPanning = true;
  41071. this.multiTouchPanAndZoom = true;
  41072. this._isPanClick = false;
  41073. this.pinchInwards = true;
  41074. }
  41075. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41076. var _this = this;
  41077. var engine = this.camera.getEngine();
  41078. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41079. var pointA = null;
  41080. var pointB = null;
  41081. var previousPinchSquaredDistance = 0;
  41082. var initialDistance = 0;
  41083. var twoFingerActivityCount = 0;
  41084. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41085. this._pointerInput = function (p, s) {
  41086. var evt = p.event;
  41087. var isTouch = p.event.pointerType === "touch";
  41088. if (engine.isInVRExclusivePointerMode) {
  41089. return;
  41090. }
  41091. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41092. return;
  41093. }
  41094. var srcElement = (evt.srcElement || evt.target);
  41095. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41096. try {
  41097. srcElement.setPointerCapture(evt.pointerId);
  41098. }
  41099. catch (e) {
  41100. //Nothing to do with the error. Execution will continue.
  41101. }
  41102. // Manage panning with pan button click
  41103. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41104. // manage pointers
  41105. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41106. if (pointA === null) {
  41107. pointA = cacheSoloPointer;
  41108. }
  41109. else if (pointB === null) {
  41110. pointB = cacheSoloPointer;
  41111. }
  41112. if (!noPreventDefault) {
  41113. evt.preventDefault();
  41114. element.focus();
  41115. }
  41116. }
  41117. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41118. _this.camera.restoreState();
  41119. }
  41120. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41121. try {
  41122. srcElement.releasePointerCapture(evt.pointerId);
  41123. }
  41124. catch (e) {
  41125. //Nothing to do with the error.
  41126. }
  41127. cacheSoloPointer = null;
  41128. previousPinchSquaredDistance = 0;
  41129. previousMultiTouchPanPosition.isPaning = false;
  41130. previousMultiTouchPanPosition.isPinching = false;
  41131. twoFingerActivityCount = 0;
  41132. initialDistance = 0;
  41133. if (!isTouch) {
  41134. pointB = null; // Mouse and pen are mono pointer
  41135. }
  41136. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41137. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41138. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41139. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41140. if (engine.badOS) {
  41141. pointA = pointB = null;
  41142. }
  41143. else {
  41144. //only remove the impacted pointer in case of multitouch allowing on most
  41145. //platforms switching from rotate to zoom and pan seamlessly.
  41146. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41147. pointA = pointB;
  41148. pointB = null;
  41149. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41150. }
  41151. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41152. pointB = null;
  41153. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41154. }
  41155. else {
  41156. pointA = pointB = null;
  41157. }
  41158. }
  41159. if (!noPreventDefault) {
  41160. evt.preventDefault();
  41161. }
  41162. }
  41163. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41164. if (!noPreventDefault) {
  41165. evt.preventDefault();
  41166. }
  41167. // One button down
  41168. if (pointA && pointB === null && cacheSoloPointer) {
  41169. if (_this.panningSensibility !== 0 &&
  41170. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41171. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41172. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41173. }
  41174. else {
  41175. var offsetX = evt.clientX - cacheSoloPointer.x;
  41176. var offsetY = evt.clientY - cacheSoloPointer.y;
  41177. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41178. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41179. }
  41180. cacheSoloPointer.x = evt.clientX;
  41181. cacheSoloPointer.y = evt.clientY;
  41182. }
  41183. else if (pointA && pointB) {
  41184. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41185. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41186. ed.x = evt.clientX;
  41187. ed.y = evt.clientY;
  41188. var direction = _this.pinchInwards ? 1 : -1;
  41189. var distX = pointA.x - pointB.x;
  41190. var distY = pointA.y - pointB.y;
  41191. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41192. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41193. if (previousPinchSquaredDistance === 0) {
  41194. initialDistance = pinchDistance;
  41195. previousPinchSquaredDistance = pinchSquaredDistance;
  41196. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41197. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41198. return;
  41199. }
  41200. if (_this.multiTouchPanAndZoom) {
  41201. if (_this.pinchDeltaPercentage) {
  41202. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41203. }
  41204. else {
  41205. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41206. (_this.pinchPrecision *
  41207. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41208. direction);
  41209. }
  41210. if (_this.panningSensibility !== 0) {
  41211. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41212. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41213. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41214. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41215. previousMultiTouchPanPosition.x = pointersCenterX;
  41216. previousMultiTouchPanPosition.y = pointersCenterY;
  41217. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41218. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41219. }
  41220. }
  41221. else {
  41222. twoFingerActivityCount++;
  41223. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41224. if (_this.pinchDeltaPercentage) {
  41225. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41226. }
  41227. else {
  41228. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41229. (_this.pinchPrecision *
  41230. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41231. direction);
  41232. }
  41233. previousMultiTouchPanPosition.isPaning = false;
  41234. previousMultiTouchPanPosition.isPinching = true;
  41235. }
  41236. else {
  41237. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41238. if (!previousMultiTouchPanPosition.isPaning) {
  41239. previousMultiTouchPanPosition.isPaning = true;
  41240. previousMultiTouchPanPosition.isPinching = false;
  41241. previousMultiTouchPanPosition.x = ed.x;
  41242. previousMultiTouchPanPosition.y = ed.y;
  41243. return;
  41244. }
  41245. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41246. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41247. }
  41248. }
  41249. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41250. previousMultiTouchPanPosition.x = ed.x;
  41251. previousMultiTouchPanPosition.y = ed.y;
  41252. }
  41253. }
  41254. previousPinchSquaredDistance = pinchSquaredDistance;
  41255. }
  41256. }
  41257. };
  41258. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41259. this._onContextMenu = function (evt) {
  41260. evt.preventDefault();
  41261. };
  41262. if (!this.camera._useCtrlForPanning) {
  41263. element.addEventListener("contextmenu", this._onContextMenu, false);
  41264. }
  41265. this._onLostFocus = function () {
  41266. //this._keys = [];
  41267. pointA = pointB = null;
  41268. previousPinchSquaredDistance = 0;
  41269. previousMultiTouchPanPosition.isPaning = false;
  41270. previousMultiTouchPanPosition.isPinching = false;
  41271. twoFingerActivityCount = 0;
  41272. cacheSoloPointer = null;
  41273. initialDistance = 0;
  41274. };
  41275. this._onMouseMove = function (evt) {
  41276. if (!engine.isPointerLock) {
  41277. return;
  41278. }
  41279. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41280. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41281. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41282. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41283. if (!noPreventDefault) {
  41284. evt.preventDefault();
  41285. }
  41286. };
  41287. this._onGestureStart = function (e) {
  41288. if (window.MSGesture === undefined) {
  41289. return;
  41290. }
  41291. if (!_this._MSGestureHandler) {
  41292. _this._MSGestureHandler = new MSGesture();
  41293. _this._MSGestureHandler.target = element;
  41294. }
  41295. _this._MSGestureHandler.addPointer(e.pointerId);
  41296. };
  41297. this._onGesture = function (e) {
  41298. _this.camera.radius *= e.scale;
  41299. if (e.preventDefault) {
  41300. if (!noPreventDefault) {
  41301. e.stopPropagation();
  41302. e.preventDefault();
  41303. }
  41304. }
  41305. };
  41306. element.addEventListener("mousemove", this._onMouseMove, false);
  41307. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41308. element.addEventListener("MSGestureChange", this._onGesture, false);
  41309. BABYLON.Tools.RegisterTopRootEvents([
  41310. { name: "blur", handler: this._onLostFocus }
  41311. ]);
  41312. };
  41313. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41314. if (this._onLostFocus) {
  41315. BABYLON.Tools.UnregisterTopRootEvents([
  41316. { name: "blur", handler: this._onLostFocus }
  41317. ]);
  41318. }
  41319. if (element && this._observer) {
  41320. this.camera.getScene().onPointerObservable.remove(this._observer);
  41321. this._observer = null;
  41322. if (this._onContextMenu) {
  41323. element.removeEventListener("contextmenu", this._onContextMenu);
  41324. }
  41325. if (this._onMouseMove) {
  41326. element.removeEventListener("mousemove", this._onMouseMove);
  41327. }
  41328. if (this._onGestureStart) {
  41329. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41330. }
  41331. if (this._onGesture) {
  41332. element.removeEventListener("MSGestureChange", this._onGesture);
  41333. }
  41334. this._isPanClick = false;
  41335. this.pinchInwards = true;
  41336. this._onMouseMove = null;
  41337. this._onGestureStart = null;
  41338. this._onGesture = null;
  41339. this._MSGestureHandler = null;
  41340. this._onLostFocus = null;
  41341. this._onContextMenu = null;
  41342. }
  41343. };
  41344. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41345. return "ArcRotateCameraPointersInput";
  41346. };
  41347. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41348. return "pointers";
  41349. };
  41350. __decorate([
  41351. BABYLON.serialize()
  41352. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41353. __decorate([
  41354. BABYLON.serialize()
  41355. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41356. __decorate([
  41357. BABYLON.serialize()
  41358. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41359. __decorate([
  41360. BABYLON.serialize()
  41361. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41362. __decorate([
  41363. BABYLON.serialize()
  41364. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41365. __decorate([
  41366. BABYLON.serialize()
  41367. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41368. __decorate([
  41369. BABYLON.serialize()
  41370. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41371. __decorate([
  41372. BABYLON.serialize()
  41373. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41374. return ArcRotateCameraPointersInput;
  41375. }());
  41376. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41377. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41378. })(BABYLON || (BABYLON = {}));
  41379. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41380. var BABYLON;
  41381. (function (BABYLON) {
  41382. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41383. __extends(ArcRotateCameraInputsManager, _super);
  41384. function ArcRotateCameraInputsManager(camera) {
  41385. return _super.call(this, camera) || this;
  41386. }
  41387. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41388. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41389. return this;
  41390. };
  41391. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41392. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41393. return this;
  41394. };
  41395. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41396. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41397. return this;
  41398. };
  41399. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41400. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41401. return this;
  41402. };
  41403. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41404. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41405. return this;
  41406. };
  41407. return ArcRotateCameraInputsManager;
  41408. }(BABYLON.CameraInputsManager));
  41409. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41410. })(BABYLON || (BABYLON = {}));
  41411. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41412. var BABYLON;
  41413. (function (BABYLON) {
  41414. var ArcRotateCamera = /** @class */ (function (_super) {
  41415. __extends(ArcRotateCamera, _super);
  41416. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41417. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41418. _this.inertialAlphaOffset = 0;
  41419. _this.inertialBetaOffset = 0;
  41420. _this.inertialRadiusOffset = 0;
  41421. _this.lowerAlphaLimit = null;
  41422. _this.upperAlphaLimit = null;
  41423. _this.lowerBetaLimit = 0.01;
  41424. _this.upperBetaLimit = Math.PI;
  41425. _this.lowerRadiusLimit = null;
  41426. _this.upperRadiusLimit = null;
  41427. _this.inertialPanningX = 0;
  41428. _this.inertialPanningY = 0;
  41429. _this.pinchToPanMaxDistance = 20;
  41430. _this.panningDistanceLimit = null;
  41431. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41432. _this.panningInertia = 0.9;
  41433. //-- end properties for backward compatibility for inputs
  41434. _this.zoomOnFactor = 1;
  41435. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41436. _this.allowUpsideDown = true;
  41437. _this._viewMatrix = new BABYLON.Matrix();
  41438. // Panning
  41439. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41440. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41441. _this.checkCollisions = false;
  41442. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41443. _this._previousPosition = BABYLON.Vector3.Zero();
  41444. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41445. _this._newPosition = BABYLON.Vector3.Zero();
  41446. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41447. if (collidedMesh === void 0) { collidedMesh = null; }
  41448. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41449. newPosition.multiplyInPlace(_this._collider._radius);
  41450. }
  41451. if (!collidedMesh) {
  41452. _this._previousPosition.copyFrom(_this.position);
  41453. }
  41454. else {
  41455. _this.setPosition(newPosition);
  41456. if (_this.onCollide) {
  41457. _this.onCollide(collidedMesh);
  41458. }
  41459. }
  41460. // Recompute because of constraints
  41461. var cosa = Math.cos(_this.alpha);
  41462. var sina = Math.sin(_this.alpha);
  41463. var cosb = Math.cos(_this.beta);
  41464. var sinb = Math.sin(_this.beta);
  41465. if (sinb === 0) {
  41466. sinb = 0.0001;
  41467. }
  41468. var target = _this._getTargetPosition();
  41469. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41470. _this.position.copyFrom(_this._newPosition);
  41471. var up = _this.upVector;
  41472. if (_this.allowUpsideDown && _this.beta < 0) {
  41473. up = up.clone();
  41474. up = up.negate();
  41475. }
  41476. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41477. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41478. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41479. _this._collisionTriggered = false;
  41480. };
  41481. _this._target = BABYLON.Vector3.Zero();
  41482. if (target) {
  41483. _this.setTarget(target);
  41484. }
  41485. _this.alpha = alpha;
  41486. _this.beta = beta;
  41487. _this.radius = radius;
  41488. _this.getViewMatrix();
  41489. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41490. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41491. return _this;
  41492. }
  41493. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41494. get: function () {
  41495. return this._target;
  41496. },
  41497. set: function (value) {
  41498. this.setTarget(value);
  41499. },
  41500. enumerable: true,
  41501. configurable: true
  41502. });
  41503. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41504. //-- begin properties for backward compatibility for inputs
  41505. get: function () {
  41506. var pointers = this.inputs.attached["pointers"];
  41507. if (pointers)
  41508. return pointers.angularSensibilityX;
  41509. return 0;
  41510. },
  41511. set: function (value) {
  41512. var pointers = this.inputs.attached["pointers"];
  41513. if (pointers) {
  41514. pointers.angularSensibilityX = value;
  41515. }
  41516. },
  41517. enumerable: true,
  41518. configurable: true
  41519. });
  41520. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41521. get: function () {
  41522. var pointers = this.inputs.attached["pointers"];
  41523. if (pointers)
  41524. return pointers.angularSensibilityY;
  41525. return 0;
  41526. },
  41527. set: function (value) {
  41528. var pointers = this.inputs.attached["pointers"];
  41529. if (pointers) {
  41530. pointers.angularSensibilityY = value;
  41531. }
  41532. },
  41533. enumerable: true,
  41534. configurable: true
  41535. });
  41536. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41537. get: function () {
  41538. var pointers = this.inputs.attached["pointers"];
  41539. if (pointers)
  41540. return pointers.pinchPrecision;
  41541. return 0;
  41542. },
  41543. set: function (value) {
  41544. var pointers = this.inputs.attached["pointers"];
  41545. if (pointers) {
  41546. pointers.pinchPrecision = value;
  41547. }
  41548. },
  41549. enumerable: true,
  41550. configurable: true
  41551. });
  41552. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41553. get: function () {
  41554. var pointers = this.inputs.attached["pointers"];
  41555. if (pointers)
  41556. return pointers.pinchDeltaPercentage;
  41557. return 0;
  41558. },
  41559. set: function (value) {
  41560. var pointers = this.inputs.attached["pointers"];
  41561. if (pointers) {
  41562. pointers.pinchDeltaPercentage = value;
  41563. }
  41564. },
  41565. enumerable: true,
  41566. configurable: true
  41567. });
  41568. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41569. get: function () {
  41570. var pointers = this.inputs.attached["pointers"];
  41571. if (pointers)
  41572. return pointers.panningSensibility;
  41573. return 0;
  41574. },
  41575. set: function (value) {
  41576. var pointers = this.inputs.attached["pointers"];
  41577. if (pointers) {
  41578. pointers.panningSensibility = value;
  41579. }
  41580. },
  41581. enumerable: true,
  41582. configurable: true
  41583. });
  41584. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41585. get: function () {
  41586. var keyboard = this.inputs.attached["keyboard"];
  41587. if (keyboard)
  41588. return keyboard.keysUp;
  41589. return [];
  41590. },
  41591. set: function (value) {
  41592. var keyboard = this.inputs.attached["keyboard"];
  41593. if (keyboard)
  41594. keyboard.keysUp = value;
  41595. },
  41596. enumerable: true,
  41597. configurable: true
  41598. });
  41599. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41600. get: function () {
  41601. var keyboard = this.inputs.attached["keyboard"];
  41602. if (keyboard)
  41603. return keyboard.keysDown;
  41604. return [];
  41605. },
  41606. set: function (value) {
  41607. var keyboard = this.inputs.attached["keyboard"];
  41608. if (keyboard)
  41609. keyboard.keysDown = value;
  41610. },
  41611. enumerable: true,
  41612. configurable: true
  41613. });
  41614. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41615. get: function () {
  41616. var keyboard = this.inputs.attached["keyboard"];
  41617. if (keyboard)
  41618. return keyboard.keysLeft;
  41619. return [];
  41620. },
  41621. set: function (value) {
  41622. var keyboard = this.inputs.attached["keyboard"];
  41623. if (keyboard)
  41624. keyboard.keysLeft = value;
  41625. },
  41626. enumerable: true,
  41627. configurable: true
  41628. });
  41629. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41630. get: function () {
  41631. var keyboard = this.inputs.attached["keyboard"];
  41632. if (keyboard)
  41633. return keyboard.keysRight;
  41634. return [];
  41635. },
  41636. set: function (value) {
  41637. var keyboard = this.inputs.attached["keyboard"];
  41638. if (keyboard)
  41639. keyboard.keysRight = value;
  41640. },
  41641. enumerable: true,
  41642. configurable: true
  41643. });
  41644. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  41645. get: function () {
  41646. var mousewheel = this.inputs.attached["mousewheel"];
  41647. if (mousewheel)
  41648. return mousewheel.wheelPrecision;
  41649. return 0;
  41650. },
  41651. set: function (value) {
  41652. var mousewheel = this.inputs.attached["mousewheel"];
  41653. if (mousewheel)
  41654. mousewheel.wheelPrecision = value;
  41655. },
  41656. enumerable: true,
  41657. configurable: true
  41658. });
  41659. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  41660. get: function () {
  41661. var mousewheel = this.inputs.attached["mousewheel"];
  41662. if (mousewheel)
  41663. return mousewheel.wheelDeltaPercentage;
  41664. return 0;
  41665. },
  41666. set: function (value) {
  41667. var mousewheel = this.inputs.attached["mousewheel"];
  41668. if (mousewheel)
  41669. mousewheel.wheelDeltaPercentage = value;
  41670. },
  41671. enumerable: true,
  41672. configurable: true
  41673. });
  41674. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  41675. get: function () {
  41676. return this._bouncingBehavior;
  41677. },
  41678. enumerable: true,
  41679. configurable: true
  41680. });
  41681. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  41682. get: function () {
  41683. return this._bouncingBehavior != null;
  41684. },
  41685. set: function (value) {
  41686. if (value === this.useBouncingBehavior) {
  41687. return;
  41688. }
  41689. if (value) {
  41690. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  41691. this.addBehavior(this._bouncingBehavior);
  41692. }
  41693. else if (this._bouncingBehavior) {
  41694. this.removeBehavior(this._bouncingBehavior);
  41695. this._bouncingBehavior = null;
  41696. }
  41697. },
  41698. enumerable: true,
  41699. configurable: true
  41700. });
  41701. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  41702. get: function () {
  41703. return this._framingBehavior;
  41704. },
  41705. enumerable: true,
  41706. configurable: true
  41707. });
  41708. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  41709. get: function () {
  41710. return this._framingBehavior != null;
  41711. },
  41712. set: function (value) {
  41713. if (value === this.useFramingBehavior) {
  41714. return;
  41715. }
  41716. if (value) {
  41717. this._framingBehavior = new BABYLON.FramingBehavior();
  41718. this.addBehavior(this._framingBehavior);
  41719. }
  41720. else if (this._framingBehavior) {
  41721. this.removeBehavior(this._framingBehavior);
  41722. this._framingBehavior = null;
  41723. }
  41724. },
  41725. enumerable: true,
  41726. configurable: true
  41727. });
  41728. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  41729. get: function () {
  41730. return this._autoRotationBehavior;
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  41736. get: function () {
  41737. return this._autoRotationBehavior != null;
  41738. },
  41739. set: function (value) {
  41740. if (value === this.useAutoRotationBehavior) {
  41741. return;
  41742. }
  41743. if (value) {
  41744. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  41745. this.addBehavior(this._autoRotationBehavior);
  41746. }
  41747. else if (this._autoRotationBehavior) {
  41748. this.removeBehavior(this._autoRotationBehavior);
  41749. this._autoRotationBehavior = null;
  41750. }
  41751. },
  41752. enumerable: true,
  41753. configurable: true
  41754. });
  41755. // Cache
  41756. ArcRotateCamera.prototype._initCache = function () {
  41757. _super.prototype._initCache.call(this);
  41758. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  41759. this._cache.alpha = undefined;
  41760. this._cache.beta = undefined;
  41761. this._cache.radius = undefined;
  41762. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  41763. };
  41764. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  41765. if (!ignoreParentClass) {
  41766. _super.prototype._updateCache.call(this);
  41767. }
  41768. this._cache._target.copyFrom(this._getTargetPosition());
  41769. this._cache.alpha = this.alpha;
  41770. this._cache.beta = this.beta;
  41771. this._cache.radius = this.radius;
  41772. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  41773. };
  41774. ArcRotateCamera.prototype._getTargetPosition = function () {
  41775. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  41776. var pos = this._targetHost.getAbsolutePosition();
  41777. if (this._targetBoundingCenter) {
  41778. pos.addToRef(this._targetBoundingCenter, this._target);
  41779. }
  41780. else {
  41781. this._target.copyFrom(pos);
  41782. }
  41783. }
  41784. var lockedTargetPosition = this._getLockedTargetPosition();
  41785. if (lockedTargetPosition) {
  41786. return lockedTargetPosition;
  41787. }
  41788. return this._target;
  41789. };
  41790. ArcRotateCamera.prototype.storeState = function () {
  41791. this._storedAlpha = this.alpha;
  41792. this._storedBeta = this.beta;
  41793. this._storedRadius = this.radius;
  41794. this._storedTarget = this._getTargetPosition().clone();
  41795. return _super.prototype.storeState.call(this);
  41796. };
  41797. /**
  41798. * Restored camera state. You must call storeState() first
  41799. */
  41800. ArcRotateCamera.prototype._restoreStateValues = function () {
  41801. if (!_super.prototype._restoreStateValues.call(this)) {
  41802. return false;
  41803. }
  41804. this.alpha = this._storedAlpha;
  41805. this.beta = this._storedBeta;
  41806. this.radius = this._storedRadius;
  41807. this.setTarget(this._storedTarget.clone());
  41808. this.inertialAlphaOffset = 0;
  41809. this.inertialBetaOffset = 0;
  41810. this.inertialRadiusOffset = 0;
  41811. this.inertialPanningX = 0;
  41812. this.inertialPanningY = 0;
  41813. return true;
  41814. };
  41815. // Synchronized
  41816. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  41817. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  41818. return false;
  41819. return this._cache._target.equals(this._getTargetPosition())
  41820. && this._cache.alpha === this.alpha
  41821. && this._cache.beta === this.beta
  41822. && this._cache.radius === this.radius
  41823. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  41824. };
  41825. // Methods
  41826. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  41827. var _this = this;
  41828. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  41829. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  41830. this._useCtrlForPanning = useCtrlForPanning;
  41831. this._panningMouseButton = panningMouseButton;
  41832. this.inputs.attachElement(element, noPreventDefault);
  41833. this._reset = function () {
  41834. _this.inertialAlphaOffset = 0;
  41835. _this.inertialBetaOffset = 0;
  41836. _this.inertialRadiusOffset = 0;
  41837. _this.inertialPanningX = 0;
  41838. _this.inertialPanningY = 0;
  41839. };
  41840. };
  41841. ArcRotateCamera.prototype.detachControl = function (element) {
  41842. this.inputs.detachElement(element);
  41843. if (this._reset) {
  41844. this._reset();
  41845. }
  41846. };
  41847. ArcRotateCamera.prototype._checkInputs = function () {
  41848. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  41849. if (this._collisionTriggered) {
  41850. return;
  41851. }
  41852. this.inputs.checkInputs();
  41853. // Inertia
  41854. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  41855. if (this.getScene().useRightHandedSystem) {
  41856. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41857. }
  41858. else {
  41859. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41860. }
  41861. this.beta += this.inertialBetaOffset;
  41862. this.radius -= this.inertialRadiusOffset;
  41863. this.inertialAlphaOffset *= this.inertia;
  41864. this.inertialBetaOffset *= this.inertia;
  41865. this.inertialRadiusOffset *= this.inertia;
  41866. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  41867. this.inertialAlphaOffset = 0;
  41868. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  41869. this.inertialBetaOffset = 0;
  41870. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  41871. this.inertialRadiusOffset = 0;
  41872. }
  41873. // Panning inertia
  41874. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  41875. if (!this._localDirection) {
  41876. this._localDirection = BABYLON.Vector3.Zero();
  41877. this._transformedDirection = BABYLON.Vector3.Zero();
  41878. }
  41879. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  41880. this._localDirection.multiplyInPlace(this.panningAxis);
  41881. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  41882. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  41883. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  41884. if (!this.panningAxis.y) {
  41885. this._transformedDirection.y = 0;
  41886. }
  41887. if (!this._targetHost) {
  41888. if (this.panningDistanceLimit) {
  41889. this._transformedDirection.addInPlace(this._target);
  41890. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  41891. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  41892. this._target.copyFrom(this._transformedDirection);
  41893. }
  41894. }
  41895. else {
  41896. this._target.addInPlace(this._transformedDirection);
  41897. }
  41898. }
  41899. this.inertialPanningX *= this.panningInertia;
  41900. this.inertialPanningY *= this.panningInertia;
  41901. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  41902. this.inertialPanningX = 0;
  41903. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  41904. this.inertialPanningY = 0;
  41905. }
  41906. // Limits
  41907. this._checkLimits();
  41908. _super.prototype._checkInputs.call(this);
  41909. };
  41910. ArcRotateCamera.prototype._checkLimits = function () {
  41911. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  41912. if (this.allowUpsideDown && this.beta > Math.PI) {
  41913. this.beta = this.beta - (2 * Math.PI);
  41914. }
  41915. }
  41916. else {
  41917. if (this.beta < this.lowerBetaLimit) {
  41918. this.beta = this.lowerBetaLimit;
  41919. }
  41920. }
  41921. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  41922. if (this.allowUpsideDown && this.beta < -Math.PI) {
  41923. this.beta = this.beta + (2 * Math.PI);
  41924. }
  41925. }
  41926. else {
  41927. if (this.beta > this.upperBetaLimit) {
  41928. this.beta = this.upperBetaLimit;
  41929. }
  41930. }
  41931. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  41932. this.alpha = this.lowerAlphaLimit;
  41933. }
  41934. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  41935. this.alpha = this.upperAlphaLimit;
  41936. }
  41937. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  41938. this.radius = this.lowerRadiusLimit;
  41939. }
  41940. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  41941. this.radius = this.upperRadiusLimit;
  41942. }
  41943. };
  41944. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  41945. var radiusv3 = this.position.subtract(this._getTargetPosition());
  41946. this.radius = radiusv3.length();
  41947. if (this.radius === 0) {
  41948. this.radius = 0.0001; // Just to avoid division by zero
  41949. }
  41950. // Alpha
  41951. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  41952. if (radiusv3.z < 0) {
  41953. this.alpha = 2 * Math.PI - this.alpha;
  41954. }
  41955. // Beta
  41956. this.beta = Math.acos(radiusv3.y / this.radius);
  41957. this._checkLimits();
  41958. };
  41959. ArcRotateCamera.prototype.setPosition = function (position) {
  41960. if (this.position.equals(position)) {
  41961. return;
  41962. }
  41963. this.position.copyFrom(position);
  41964. this.rebuildAnglesAndRadius();
  41965. };
  41966. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  41967. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  41968. if (allowSamePosition === void 0) { allowSamePosition = false; }
  41969. if (target.getBoundingInfo) {
  41970. if (toBoundingCenter) {
  41971. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  41972. }
  41973. else {
  41974. this._targetBoundingCenter = null;
  41975. }
  41976. this._targetHost = target;
  41977. this._target = this._getTargetPosition();
  41978. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  41979. }
  41980. else {
  41981. var newTarget = target;
  41982. var currentTarget = this._getTargetPosition();
  41983. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  41984. return;
  41985. }
  41986. this._targetHost = null;
  41987. this._target = newTarget;
  41988. this._targetBoundingCenter = null;
  41989. this.onMeshTargetChangedObservable.notifyObservers(null);
  41990. }
  41991. this.rebuildAnglesAndRadius();
  41992. };
  41993. ArcRotateCamera.prototype._getViewMatrix = function () {
  41994. // Compute
  41995. var cosa = Math.cos(this.alpha);
  41996. var sina = Math.sin(this.alpha);
  41997. var cosb = Math.cos(this.beta);
  41998. var sinb = Math.sin(this.beta);
  41999. if (sinb === 0) {
  42000. sinb = 0.0001;
  42001. }
  42002. var target = this._getTargetPosition();
  42003. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42004. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42005. if (!this._collider) {
  42006. this._collider = new BABYLON.Collider();
  42007. }
  42008. this._collider._radius = this.collisionRadius;
  42009. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42010. this._collisionTriggered = true;
  42011. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42012. }
  42013. else {
  42014. this.position.copyFrom(this._newPosition);
  42015. var up = this.upVector;
  42016. if (this.allowUpsideDown && sinb < 0) {
  42017. up = up.clone();
  42018. up = up.negate();
  42019. }
  42020. if (this.getScene().useRightHandedSystem) {
  42021. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42022. }
  42023. else {
  42024. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42025. }
  42026. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42027. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42028. }
  42029. this._currentTarget = target;
  42030. return this._viewMatrix;
  42031. };
  42032. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42033. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42034. meshes = meshes || this.getScene().meshes;
  42035. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42036. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42037. this.radius = distance * this.zoomOnFactor;
  42038. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42039. };
  42040. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42041. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42042. var meshesOrMinMaxVector;
  42043. var distance;
  42044. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42045. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42046. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42047. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42048. }
  42049. else {
  42050. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42051. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42052. distance = minMaxVectorAndDistance.distance;
  42053. }
  42054. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42055. if (!doNotUpdateMaxZ) {
  42056. this.maxZ = distance * 2;
  42057. }
  42058. };
  42059. /**
  42060. * @override
  42061. * Override Camera.createRigCamera
  42062. */
  42063. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42064. var alphaShift = 0;
  42065. switch (this.cameraRigMode) {
  42066. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42067. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42068. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42069. case BABYLON.Camera.RIG_MODE_VR:
  42070. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42071. break;
  42072. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42073. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42074. break;
  42075. }
  42076. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42077. rigCam._cameraRigParams = {};
  42078. return rigCam;
  42079. };
  42080. /**
  42081. * @override
  42082. * Override Camera._updateRigCameras
  42083. */
  42084. ArcRotateCamera.prototype._updateRigCameras = function () {
  42085. var camLeft = this._rigCameras[0];
  42086. var camRight = this._rigCameras[1];
  42087. camLeft.beta = camRight.beta = this.beta;
  42088. camLeft.radius = camRight.radius = this.radius;
  42089. switch (this.cameraRigMode) {
  42090. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42091. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42092. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42093. case BABYLON.Camera.RIG_MODE_VR:
  42094. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42095. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42096. break;
  42097. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42098. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42099. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42100. break;
  42101. }
  42102. _super.prototype._updateRigCameras.call(this);
  42103. };
  42104. ArcRotateCamera.prototype.dispose = function () {
  42105. this.inputs.clear();
  42106. _super.prototype.dispose.call(this);
  42107. };
  42108. ArcRotateCamera.prototype.getClassName = function () {
  42109. return "ArcRotateCamera";
  42110. };
  42111. __decorate([
  42112. BABYLON.serialize()
  42113. ], ArcRotateCamera.prototype, "alpha", void 0);
  42114. __decorate([
  42115. BABYLON.serialize()
  42116. ], ArcRotateCamera.prototype, "beta", void 0);
  42117. __decorate([
  42118. BABYLON.serialize()
  42119. ], ArcRotateCamera.prototype, "radius", void 0);
  42120. __decorate([
  42121. BABYLON.serializeAsVector3("target")
  42122. ], ArcRotateCamera.prototype, "_target", void 0);
  42123. __decorate([
  42124. BABYLON.serialize()
  42125. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42126. __decorate([
  42127. BABYLON.serialize()
  42128. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42129. __decorate([
  42130. BABYLON.serialize()
  42131. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42132. __decorate([
  42133. BABYLON.serialize()
  42134. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42135. __decorate([
  42136. BABYLON.serialize()
  42137. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42138. __decorate([
  42139. BABYLON.serialize()
  42140. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42141. __decorate([
  42142. BABYLON.serialize()
  42143. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42144. __decorate([
  42145. BABYLON.serialize()
  42146. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42147. __decorate([
  42148. BABYLON.serialize()
  42149. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42150. __decorate([
  42151. BABYLON.serialize()
  42152. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42153. __decorate([
  42154. BABYLON.serialize()
  42155. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42156. __decorate([
  42157. BABYLON.serialize()
  42158. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42159. __decorate([
  42160. BABYLON.serialize()
  42161. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42162. __decorate([
  42163. BABYLON.serializeAsVector3()
  42164. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42165. __decorate([
  42166. BABYLON.serialize()
  42167. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42168. __decorate([
  42169. BABYLON.serialize()
  42170. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42171. __decorate([
  42172. BABYLON.serialize()
  42173. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42174. return ArcRotateCamera;
  42175. }(BABYLON.TargetCamera));
  42176. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42177. })(BABYLON || (BABYLON = {}));
  42178. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42179. var BABYLON;
  42180. (function (BABYLON) {
  42181. var HemisphericLight = /** @class */ (function (_super) {
  42182. __extends(HemisphericLight, _super);
  42183. /**
  42184. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42185. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42186. * The HemisphericLight can't cast shadows.
  42187. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42188. */
  42189. function HemisphericLight(name, direction, scene) {
  42190. var _this = _super.call(this, name, scene) || this;
  42191. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42192. _this.direction = direction || BABYLON.Vector3.Up();
  42193. return _this;
  42194. }
  42195. HemisphericLight.prototype._buildUniformLayout = function () {
  42196. this._uniformBuffer.addUniform("vLightData", 4);
  42197. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42198. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42199. this._uniformBuffer.addUniform("vLightGround", 3);
  42200. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42201. this._uniformBuffer.addUniform("depthValues", 2);
  42202. this._uniformBuffer.create();
  42203. };
  42204. /**
  42205. * Returns the string "HemisphericLight".
  42206. */
  42207. HemisphericLight.prototype.getClassName = function () {
  42208. return "HemisphericLight";
  42209. };
  42210. /**
  42211. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42212. * Returns the updated direction.
  42213. */
  42214. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42215. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42216. return this.direction;
  42217. };
  42218. HemisphericLight.prototype.getShadowGenerator = function () {
  42219. return null;
  42220. };
  42221. /**
  42222. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42223. * Returns the HemisphericLight.
  42224. */
  42225. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42226. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42227. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42228. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42229. return this;
  42230. };
  42231. HemisphericLight.prototype._getWorldMatrix = function () {
  42232. if (!this._worldMatrix) {
  42233. this._worldMatrix = BABYLON.Matrix.Identity();
  42234. }
  42235. return this._worldMatrix;
  42236. };
  42237. /**
  42238. * Returns the integer 3.
  42239. */
  42240. HemisphericLight.prototype.getTypeID = function () {
  42241. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42242. };
  42243. __decorate([
  42244. BABYLON.serializeAsColor3()
  42245. ], HemisphericLight.prototype, "groundColor", void 0);
  42246. __decorate([
  42247. BABYLON.serializeAsVector3()
  42248. ], HemisphericLight.prototype, "direction", void 0);
  42249. return HemisphericLight;
  42250. }(BABYLON.Light));
  42251. BABYLON.HemisphericLight = HemisphericLight;
  42252. })(BABYLON || (BABYLON = {}));
  42253. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42254. var BABYLON;
  42255. (function (BABYLON) {
  42256. var ShadowLight = /** @class */ (function (_super) {
  42257. __extends(ShadowLight, _super);
  42258. function ShadowLight() {
  42259. var _this = _super !== null && _super.apply(this, arguments) || this;
  42260. _this._needProjectionMatrixCompute = true;
  42261. return _this;
  42262. }
  42263. Object.defineProperty(ShadowLight.prototype, "direction", {
  42264. get: function () {
  42265. return this._direction;
  42266. },
  42267. set: function (value) {
  42268. this._direction = value;
  42269. },
  42270. enumerable: true,
  42271. configurable: true
  42272. });
  42273. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42274. get: function () {
  42275. return this._shadowMinZ;
  42276. },
  42277. set: function (value) {
  42278. this._shadowMinZ = value;
  42279. this.forceProjectionMatrixCompute();
  42280. },
  42281. enumerable: true,
  42282. configurable: true
  42283. });
  42284. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42285. get: function () {
  42286. return this._shadowMaxZ;
  42287. },
  42288. set: function (value) {
  42289. this._shadowMaxZ = value;
  42290. this.forceProjectionMatrixCompute();
  42291. },
  42292. enumerable: true,
  42293. configurable: true
  42294. });
  42295. /**
  42296. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  42297. */
  42298. ShadowLight.prototype.computeTransformedInformation = function () {
  42299. if (this.parent && this.parent.getWorldMatrix) {
  42300. if (!this.transformedPosition) {
  42301. this.transformedPosition = BABYLON.Vector3.Zero();
  42302. }
  42303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42304. // In case the direction is present.
  42305. if (this.direction) {
  42306. if (!this.transformedDirection) {
  42307. this.transformedDirection = BABYLON.Vector3.Zero();
  42308. }
  42309. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42310. }
  42311. return true;
  42312. }
  42313. return false;
  42314. };
  42315. /**
  42316. * Return the depth scale used for the shadow map.
  42317. */
  42318. ShadowLight.prototype.getDepthScale = function () {
  42319. return 50.0;
  42320. };
  42321. /**
  42322. * Returns the light direction (Vector3) for any passed face index.
  42323. */
  42324. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42325. return this.transformedDirection ? this.transformedDirection : this.direction;
  42326. };
  42327. /**
  42328. * Returns the ShadowLight absolute position in the World.
  42329. */
  42330. ShadowLight.prototype.getAbsolutePosition = function () {
  42331. return this.transformedPosition ? this.transformedPosition : this.position;
  42332. };
  42333. /**
  42334. * Sets the ShadowLight direction toward the passed target (Vector3).
  42335. * Returns the updated ShadowLight direction (Vector3).
  42336. */
  42337. ShadowLight.prototype.setDirectionToTarget = function (target) {
  42338. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  42339. return this.direction;
  42340. };
  42341. /**
  42342. * Returns the light rotation (Vector3).
  42343. */
  42344. ShadowLight.prototype.getRotation = function () {
  42345. this.direction.normalize();
  42346. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  42347. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  42348. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  42349. };
  42350. /**
  42351. * Boolean : false by default.
  42352. */
  42353. ShadowLight.prototype.needCube = function () {
  42354. return false;
  42355. };
  42356. /**
  42357. * Specifies wether or not the projection matrix should be recomputed this frame.
  42358. */
  42359. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  42360. return this._needProjectionMatrixCompute;
  42361. };
  42362. /**
  42363. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  42364. */
  42365. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  42366. this._needProjectionMatrixCompute = true;
  42367. };
  42368. /**
  42369. * Get the world matrix of the sahdow lights.
  42370. */
  42371. ShadowLight.prototype._getWorldMatrix = function () {
  42372. if (!this._worldMatrix) {
  42373. this._worldMatrix = BABYLON.Matrix.Identity();
  42374. }
  42375. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42376. return this._worldMatrix;
  42377. };
  42378. /**
  42379. * Gets the minZ used for shadow according to both the scene and the light.
  42380. * @param activeCamera
  42381. */
  42382. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42383. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42384. };
  42385. /**
  42386. * Gets the maxZ used for shadow according to both the scene and the light.
  42387. * @param activeCamera
  42388. */
  42389. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42390. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42391. };
  42392. /**
  42393. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42394. * Returns the light.
  42395. */
  42396. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42397. if (this.customProjectionMatrixBuilder) {
  42398. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42399. }
  42400. else {
  42401. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42402. }
  42403. return this;
  42404. };
  42405. __decorate([
  42406. BABYLON.serializeAsVector3()
  42407. ], ShadowLight.prototype, "position", void 0);
  42408. __decorate([
  42409. BABYLON.serializeAsVector3()
  42410. ], ShadowLight.prototype, "direction", null);
  42411. __decorate([
  42412. BABYLON.serialize()
  42413. ], ShadowLight.prototype, "shadowMinZ", null);
  42414. __decorate([
  42415. BABYLON.serialize()
  42416. ], ShadowLight.prototype, "shadowMaxZ", null);
  42417. return ShadowLight;
  42418. }(BABYLON.Light));
  42419. BABYLON.ShadowLight = ShadowLight;
  42420. })(BABYLON || (BABYLON = {}));
  42421. //# sourceMappingURL=babylon.shadowLight.js.map
  42422. var BABYLON;
  42423. (function (BABYLON) {
  42424. var PointLight = /** @class */ (function (_super) {
  42425. __extends(PointLight, _super);
  42426. /**
  42427. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42428. * A PointLight emits the light in every direction.
  42429. * It can cast shadows.
  42430. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42431. * ```javascript
  42432. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42433. * ```
  42434. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42435. */
  42436. function PointLight(name, position, scene) {
  42437. var _this = _super.call(this, name, scene) || this;
  42438. _this._shadowAngle = Math.PI / 2;
  42439. _this.position = position;
  42440. return _this;
  42441. }
  42442. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42443. /**
  42444. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42445. * This specifies what angle the shadow will use to be created.
  42446. *
  42447. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42448. */
  42449. get: function () {
  42450. return this._shadowAngle;
  42451. },
  42452. /**
  42453. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42454. * This specifies what angle the shadow will use to be created.
  42455. *
  42456. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42457. */
  42458. set: function (value) {
  42459. this._shadowAngle = value;
  42460. this.forceProjectionMatrixCompute();
  42461. },
  42462. enumerable: true,
  42463. configurable: true
  42464. });
  42465. Object.defineProperty(PointLight.prototype, "direction", {
  42466. get: function () {
  42467. return this._direction;
  42468. },
  42469. /**
  42470. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42471. */
  42472. set: function (value) {
  42473. var previousNeedCube = this.needCube();
  42474. this._direction = value;
  42475. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42476. this._shadowGenerator.recreateShadowMap();
  42477. }
  42478. },
  42479. enumerable: true,
  42480. configurable: true
  42481. });
  42482. /**
  42483. * Returns the string "PointLight"
  42484. */
  42485. PointLight.prototype.getClassName = function () {
  42486. return "PointLight";
  42487. };
  42488. /**
  42489. * Returns the integer 0.
  42490. */
  42491. PointLight.prototype.getTypeID = function () {
  42492. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42493. };
  42494. /**
  42495. * Specifies wether or not the shadowmap should be a cube texture.
  42496. */
  42497. PointLight.prototype.needCube = function () {
  42498. return !this.direction;
  42499. };
  42500. /**
  42501. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42502. */
  42503. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42504. if (this.direction) {
  42505. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42506. }
  42507. else {
  42508. switch (faceIndex) {
  42509. case 0:
  42510. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42511. case 1:
  42512. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42513. case 2:
  42514. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42515. case 3:
  42516. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42517. case 4:
  42518. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42519. case 5:
  42520. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42521. }
  42522. }
  42523. return BABYLON.Vector3.Zero();
  42524. };
  42525. /**
  42526. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42527. * - fov = PI / 2
  42528. * - aspect ratio : 1.0
  42529. * - z-near and far equal to the active camera minZ and maxZ.
  42530. * Returns the PointLight.
  42531. */
  42532. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42533. var activeCamera = this.getScene().activeCamera;
  42534. if (!activeCamera) {
  42535. return;
  42536. }
  42537. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42538. };
  42539. PointLight.prototype._buildUniformLayout = function () {
  42540. this._uniformBuffer.addUniform("vLightData", 4);
  42541. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42542. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42543. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42544. this._uniformBuffer.addUniform("depthValues", 2);
  42545. this._uniformBuffer.create();
  42546. };
  42547. /**
  42548. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42549. * Returns the PointLight.
  42550. */
  42551. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42552. if (this.computeTransformedInformation()) {
  42553. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42554. return this;
  42555. }
  42556. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42557. return this;
  42558. };
  42559. __decorate([
  42560. BABYLON.serialize()
  42561. ], PointLight.prototype, "shadowAngle", null);
  42562. return PointLight;
  42563. }(BABYLON.ShadowLight));
  42564. BABYLON.PointLight = PointLight;
  42565. })(BABYLON || (BABYLON = {}));
  42566. //# sourceMappingURL=babylon.pointLight.js.map
  42567. var BABYLON;
  42568. (function (BABYLON) {
  42569. var DirectionalLight = /** @class */ (function (_super) {
  42570. __extends(DirectionalLight, _super);
  42571. /**
  42572. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42573. * The directional light is emitted from everywhere in the given direction.
  42574. * It can cast shawdows.
  42575. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42576. */
  42577. function DirectionalLight(name, direction, scene) {
  42578. var _this = _super.call(this, name, scene) || this;
  42579. _this._shadowFrustumSize = 0;
  42580. _this._shadowOrthoScale = 0.5;
  42581. _this.autoUpdateExtends = true;
  42582. // Cache
  42583. _this._orthoLeft = Number.MAX_VALUE;
  42584. _this._orthoRight = Number.MIN_VALUE;
  42585. _this._orthoTop = Number.MIN_VALUE;
  42586. _this._orthoBottom = Number.MAX_VALUE;
  42587. _this.position = direction.scale(-1.0);
  42588. _this.direction = direction;
  42589. return _this;
  42590. }
  42591. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42592. /**
  42593. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42594. */
  42595. get: function () {
  42596. return this._shadowFrustumSize;
  42597. },
  42598. /**
  42599. * Specifies a fix frustum size for the shadow generation.
  42600. */
  42601. set: function (value) {
  42602. this._shadowFrustumSize = value;
  42603. this.forceProjectionMatrixCompute();
  42604. },
  42605. enumerable: true,
  42606. configurable: true
  42607. });
  42608. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42609. get: function () {
  42610. return this._shadowOrthoScale;
  42611. },
  42612. set: function (value) {
  42613. this._shadowOrthoScale = value;
  42614. this.forceProjectionMatrixCompute();
  42615. },
  42616. enumerable: true,
  42617. configurable: true
  42618. });
  42619. /**
  42620. * Returns the string "DirectionalLight".
  42621. */
  42622. DirectionalLight.prototype.getClassName = function () {
  42623. return "DirectionalLight";
  42624. };
  42625. /**
  42626. * Returns the integer 1.
  42627. */
  42628. DirectionalLight.prototype.getTypeID = function () {
  42629. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42630. };
  42631. /**
  42632. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42633. * Returns the DirectionalLight Shadow projection matrix.
  42634. */
  42635. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42636. if (this.shadowFrustumSize > 0) {
  42637. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  42638. }
  42639. else {
  42640. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42641. }
  42642. };
  42643. /**
  42644. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  42645. * Returns the DirectionalLight Shadow projection matrix.
  42646. */
  42647. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  42648. var activeCamera = this.getScene().activeCamera;
  42649. if (!activeCamera) {
  42650. return;
  42651. }
  42652. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  42653. };
  42654. /**
  42655. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  42656. * Returns the DirectionalLight Shadow projection matrix.
  42657. */
  42658. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42659. var activeCamera = this.getScene().activeCamera;
  42660. if (!activeCamera) {
  42661. return;
  42662. }
  42663. // Check extends
  42664. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  42665. var tempVector3 = BABYLON.Vector3.Zero();
  42666. this._orthoLeft = Number.MAX_VALUE;
  42667. this._orthoRight = Number.MIN_VALUE;
  42668. this._orthoTop = Number.MIN_VALUE;
  42669. this._orthoBottom = Number.MAX_VALUE;
  42670. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  42671. var mesh = renderList[meshIndex];
  42672. if (!mesh) {
  42673. continue;
  42674. }
  42675. var boundingInfo = mesh.getBoundingInfo();
  42676. var boundingBox = boundingInfo.boundingBox;
  42677. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  42678. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  42679. if (tempVector3.x < this._orthoLeft)
  42680. this._orthoLeft = tempVector3.x;
  42681. if (tempVector3.y < this._orthoBottom)
  42682. this._orthoBottom = tempVector3.y;
  42683. if (tempVector3.x > this._orthoRight)
  42684. this._orthoRight = tempVector3.x;
  42685. if (tempVector3.y > this._orthoTop)
  42686. this._orthoTop = tempVector3.y;
  42687. }
  42688. }
  42689. }
  42690. var xOffset = this._orthoRight - this._orthoLeft;
  42691. var yOffset = this._orthoTop - this._orthoBottom;
  42692. 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);
  42693. };
  42694. DirectionalLight.prototype._buildUniformLayout = function () {
  42695. this._uniformBuffer.addUniform("vLightData", 4);
  42696. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42697. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42698. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42699. this._uniformBuffer.addUniform("depthValues", 2);
  42700. this._uniformBuffer.create();
  42701. };
  42702. /**
  42703. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  42704. * Returns the DirectionalLight.
  42705. */
  42706. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  42707. if (this.computeTransformedInformation()) {
  42708. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  42709. return this;
  42710. }
  42711. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  42712. return this;
  42713. };
  42714. /**
  42715. * Gets the minZ used for shadow according to both the scene and the light.
  42716. *
  42717. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42718. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42719. * @param activeCamera
  42720. */
  42721. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  42722. return 1;
  42723. };
  42724. /**
  42725. * Gets the maxZ used for shadow according to both the scene and the light.
  42726. *
  42727. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42728. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42729. * @param activeCamera
  42730. */
  42731. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  42732. return 1;
  42733. };
  42734. __decorate([
  42735. BABYLON.serialize()
  42736. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  42737. __decorate([
  42738. BABYLON.serialize()
  42739. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  42740. __decorate([
  42741. BABYLON.serialize()
  42742. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  42743. return DirectionalLight;
  42744. }(BABYLON.ShadowLight));
  42745. BABYLON.DirectionalLight = DirectionalLight;
  42746. })(BABYLON || (BABYLON = {}));
  42747. //# sourceMappingURL=babylon.directionalLight.js.map
  42748. var BABYLON;
  42749. (function (BABYLON) {
  42750. var SpotLight = /** @class */ (function (_super) {
  42751. __extends(SpotLight, _super);
  42752. /**
  42753. * Creates a SpotLight object in the scene with the passed parameters :
  42754. * - `position` (Vector3) is the initial SpotLight position,
  42755. * - `direction` (Vector3) is the initial SpotLight direction,
  42756. * - `angle` (float, in radians) is the spot light cone angle,
  42757. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  42758. * A spot light is a simply light oriented cone.
  42759. * It can cast shadows.
  42760. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42761. */
  42762. function SpotLight(name, position, direction, angle, exponent, scene) {
  42763. var _this = _super.call(this, name, scene) || this;
  42764. _this.position = position;
  42765. _this.direction = direction;
  42766. _this.angle = angle;
  42767. _this.exponent = exponent;
  42768. return _this;
  42769. }
  42770. Object.defineProperty(SpotLight.prototype, "angle", {
  42771. get: function () {
  42772. return this._angle;
  42773. },
  42774. set: function (value) {
  42775. this._angle = value;
  42776. this.forceProjectionMatrixCompute();
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  42782. get: function () {
  42783. return this._shadowAngleScale;
  42784. },
  42785. /**
  42786. * Allows scaling the angle of the light for shadow generation only.
  42787. */
  42788. set: function (value) {
  42789. this._shadowAngleScale = value;
  42790. this.forceProjectionMatrixCompute();
  42791. },
  42792. enumerable: true,
  42793. configurable: true
  42794. });
  42795. /**
  42796. * Returns the string "SpotLight".
  42797. */
  42798. SpotLight.prototype.getClassName = function () {
  42799. return "SpotLight";
  42800. };
  42801. /**
  42802. * Returns the integer 2.
  42803. */
  42804. SpotLight.prototype.getTypeID = function () {
  42805. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  42806. };
  42807. /**
  42808. * 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.
  42809. * Returns the SpotLight.
  42810. */
  42811. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42812. var activeCamera = this.getScene().activeCamera;
  42813. if (!activeCamera) {
  42814. return;
  42815. }
  42816. this._shadowAngleScale = this._shadowAngleScale || 1;
  42817. var angle = this._shadowAngleScale * this._angle;
  42818. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42819. };
  42820. SpotLight.prototype._buildUniformLayout = function () {
  42821. this._uniformBuffer.addUniform("vLightData", 4);
  42822. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42823. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42824. this._uniformBuffer.addUniform("vLightDirection", 3);
  42825. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42826. this._uniformBuffer.addUniform("depthValues", 2);
  42827. this._uniformBuffer.create();
  42828. };
  42829. /**
  42830. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  42831. * Return the SpotLight.
  42832. */
  42833. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  42834. var normalizeDirection;
  42835. if (this.computeTransformedInformation()) {
  42836. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  42837. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  42838. }
  42839. else {
  42840. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  42841. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42842. }
  42843. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  42844. return this;
  42845. };
  42846. __decorate([
  42847. BABYLON.serialize()
  42848. ], SpotLight.prototype, "angle", null);
  42849. __decorate([
  42850. BABYLON.serialize()
  42851. /**
  42852. * Allows scaling the angle of the light for shadow generation only.
  42853. */
  42854. ], SpotLight.prototype, "shadowAngleScale", null);
  42855. __decorate([
  42856. BABYLON.serialize()
  42857. ], SpotLight.prototype, "exponent", void 0);
  42858. return SpotLight;
  42859. }(BABYLON.ShadowLight));
  42860. BABYLON.SpotLight = SpotLight;
  42861. })(BABYLON || (BABYLON = {}));
  42862. //# sourceMappingURL=babylon.spotLight.js.map
  42863. var BABYLON;
  42864. (function (BABYLON) {
  42865. var AnimationRange = /** @class */ (function () {
  42866. function AnimationRange(name, from, to) {
  42867. this.name = name;
  42868. this.from = from;
  42869. this.to = to;
  42870. }
  42871. AnimationRange.prototype.clone = function () {
  42872. return new AnimationRange(this.name, this.from, this.to);
  42873. };
  42874. return AnimationRange;
  42875. }());
  42876. BABYLON.AnimationRange = AnimationRange;
  42877. /**
  42878. * Composed of a frame, and an action function
  42879. */
  42880. var AnimationEvent = /** @class */ (function () {
  42881. function AnimationEvent(frame, action, onlyOnce) {
  42882. this.frame = frame;
  42883. this.action = action;
  42884. this.onlyOnce = onlyOnce;
  42885. this.isDone = false;
  42886. }
  42887. return AnimationEvent;
  42888. }());
  42889. BABYLON.AnimationEvent = AnimationEvent;
  42890. var PathCursor = /** @class */ (function () {
  42891. function PathCursor(path) {
  42892. this.path = path;
  42893. this._onchange = new Array();
  42894. this.value = 0;
  42895. this.animations = new Array();
  42896. }
  42897. PathCursor.prototype.getPoint = function () {
  42898. var point = this.path.getPointAtLengthPosition(this.value);
  42899. return new BABYLON.Vector3(point.x, 0, point.y);
  42900. };
  42901. PathCursor.prototype.moveAhead = function (step) {
  42902. if (step === void 0) { step = 0.002; }
  42903. this.move(step);
  42904. return this;
  42905. };
  42906. PathCursor.prototype.moveBack = function (step) {
  42907. if (step === void 0) { step = 0.002; }
  42908. this.move(-step);
  42909. return this;
  42910. };
  42911. PathCursor.prototype.move = function (step) {
  42912. if (Math.abs(step) > 1) {
  42913. throw "step size should be less than 1.";
  42914. }
  42915. this.value += step;
  42916. this.ensureLimits();
  42917. this.raiseOnChange();
  42918. return this;
  42919. };
  42920. PathCursor.prototype.ensureLimits = function () {
  42921. while (this.value > 1) {
  42922. this.value -= 1;
  42923. }
  42924. while (this.value < 0) {
  42925. this.value += 1;
  42926. }
  42927. return this;
  42928. };
  42929. // used by animation engine
  42930. PathCursor.prototype.raiseOnChange = function () {
  42931. var _this = this;
  42932. this._onchange.forEach(function (f) { return f(_this); });
  42933. return this;
  42934. };
  42935. PathCursor.prototype.onchange = function (f) {
  42936. this._onchange.push(f);
  42937. return this;
  42938. };
  42939. return PathCursor;
  42940. }());
  42941. BABYLON.PathCursor = PathCursor;
  42942. var AnimationKeyInterpolation;
  42943. (function (AnimationKeyInterpolation) {
  42944. /**
  42945. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  42946. */
  42947. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  42948. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  42949. var Animation = /** @class */ (function () {
  42950. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  42951. this.name = name;
  42952. this.targetProperty = targetProperty;
  42953. this.framePerSecond = framePerSecond;
  42954. this.dataType = dataType;
  42955. this.loopMode = loopMode;
  42956. this.enableBlending = enableBlending;
  42957. this._runtimeAnimations = new Array();
  42958. // The set of event that will be linked to this animation
  42959. this._events = new Array();
  42960. this.blendingSpeed = 0.01;
  42961. this._ranges = {};
  42962. this.targetPropertyPath = targetProperty.split(".");
  42963. this.dataType = dataType;
  42964. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  42965. }
  42966. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  42967. var dataType = undefined;
  42968. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  42969. dataType = Animation.ANIMATIONTYPE_FLOAT;
  42970. }
  42971. else if (from instanceof BABYLON.Quaternion) {
  42972. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  42973. }
  42974. else if (from instanceof BABYLON.Vector3) {
  42975. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  42976. }
  42977. else if (from instanceof BABYLON.Vector2) {
  42978. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  42979. }
  42980. else if (from instanceof BABYLON.Color3) {
  42981. dataType = Animation.ANIMATIONTYPE_COLOR3;
  42982. }
  42983. else if (from instanceof BABYLON.Size) {
  42984. dataType = Animation.ANIMATIONTYPE_SIZE;
  42985. }
  42986. if (dataType == undefined) {
  42987. return null;
  42988. }
  42989. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  42990. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  42991. animation.setKeys(keys);
  42992. if (easingFunction !== undefined) {
  42993. animation.setEasingFunction(easingFunction);
  42994. }
  42995. return animation;
  42996. };
  42997. /**
  42998. * Sets up an animation.
  42999. * @param property the property to animate
  43000. * @param animationType the animation type to apply
  43001. * @param easingFunction the easing function used in the animation
  43002. * @returns The created animation
  43003. */
  43004. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43005. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43006. animation.setEasingFunction(easingFunction);
  43007. return animation;
  43008. };
  43009. /**
  43010. * Create and start an animation on a node
  43011. * @param {string} name defines the name of the global animation that will be run on all nodes
  43012. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43013. * @param {string} targetProperty defines property to animate
  43014. * @param {number} framePerSecond defines the number of frame per second yo use
  43015. * @param {number} totalFrame defines the number of frames in total
  43016. * @param {any} from defines the initial value
  43017. * @param {any} to defines the final value
  43018. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43019. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43020. * @param onAnimationEnd defines the callback to call when animation end
  43021. * @returns the animatable created for this animation
  43022. */
  43023. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43024. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43025. if (!animation) {
  43026. return null;
  43027. }
  43028. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43029. };
  43030. /**
  43031. * Create and start an animation on a node and its descendants
  43032. * @param {string} name defines the name of the global animation that will be run on all nodes
  43033. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43034. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  43035. * @param {string} targetProperty defines property to animate
  43036. * @param {number} framePerSecond defines the number of frame per second yo use
  43037. * @param {number} totalFrame defines the number of frames in total
  43038. * @param {any} from defines the initial value
  43039. * @param {any} to defines the final value
  43040. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43041. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43042. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43043. * @returns the list of animatables created for all nodes
  43044. * @example https://www.babylonjs-playground.com/#MH0VLI
  43045. */
  43046. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43047. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43048. if (!animation) {
  43049. return null;
  43050. }
  43051. var scene = node.getScene();
  43052. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43053. };
  43054. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43055. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43056. if (!animation) {
  43057. return null;
  43058. }
  43059. node.animations.push(animation);
  43060. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43061. };
  43062. /**
  43063. * Transition property of the Camera to the target Value.
  43064. * @param property The property to transition
  43065. * @param targetValue The target Value of the property
  43066. * @param host The object where the property to animate belongs
  43067. * @param scene Scene used to run the animation
  43068. * @param frameRate Framerate (in frame/s) to use
  43069. * @param transition The transition type we want to use
  43070. * @param duration The duration of the animation, in milliseconds
  43071. * @param onAnimationEnd Call back trigger at the end of the animation.
  43072. */
  43073. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43074. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43075. if (duration <= 0) {
  43076. host[property] = targetValue;
  43077. if (onAnimationEnd) {
  43078. onAnimationEnd();
  43079. }
  43080. return null;
  43081. }
  43082. var endFrame = frameRate * (duration / 1000);
  43083. transition.setKeys([{
  43084. frame: 0,
  43085. value: host[property].clone ? host[property].clone() : host[property]
  43086. },
  43087. {
  43088. frame: endFrame,
  43089. value: targetValue
  43090. }]);
  43091. if (!host.animations) {
  43092. host.animations = [];
  43093. }
  43094. host.animations.push(transition);
  43095. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43096. animation.onAnimationEnd = onAnimationEnd;
  43097. return animation;
  43098. };
  43099. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43100. /**
  43101. * Return the array of runtime animations currently using this animation
  43102. */
  43103. get: function () {
  43104. return this._runtimeAnimations;
  43105. },
  43106. enumerable: true,
  43107. configurable: true
  43108. });
  43109. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43110. get: function () {
  43111. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43112. var runtimeAnimation = _a[_i];
  43113. if (!runtimeAnimation.isStopped) {
  43114. return true;
  43115. }
  43116. }
  43117. return false;
  43118. },
  43119. enumerable: true,
  43120. configurable: true
  43121. });
  43122. // Methods
  43123. /**
  43124. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43125. */
  43126. Animation.prototype.toString = function (fullDetails) {
  43127. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43128. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43129. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43130. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  43131. if (fullDetails) {
  43132. ret += ", Ranges: {";
  43133. var first = true;
  43134. for (var name in this._ranges) {
  43135. if (first) {
  43136. ret += ", ";
  43137. first = false;
  43138. }
  43139. ret += name;
  43140. }
  43141. ret += "}";
  43142. }
  43143. return ret;
  43144. };
  43145. /**
  43146. * Add an event to this animation.
  43147. */
  43148. Animation.prototype.addEvent = function (event) {
  43149. this._events.push(event);
  43150. };
  43151. /**
  43152. * Remove all events found at the given frame
  43153. * @param frame
  43154. */
  43155. Animation.prototype.removeEvents = function (frame) {
  43156. for (var index = 0; index < this._events.length; index++) {
  43157. if (this._events[index].frame === frame) {
  43158. this._events.splice(index, 1);
  43159. index--;
  43160. }
  43161. }
  43162. };
  43163. Animation.prototype.getEvents = function () {
  43164. return this._events;
  43165. };
  43166. Animation.prototype.createRange = function (name, from, to) {
  43167. // check name not already in use; could happen for bones after serialized
  43168. if (!this._ranges[name]) {
  43169. this._ranges[name] = new AnimationRange(name, from, to);
  43170. }
  43171. };
  43172. Animation.prototype.deleteRange = function (name, deleteFrames) {
  43173. if (deleteFrames === void 0) { deleteFrames = true; }
  43174. var range = this._ranges[name];
  43175. if (!range) {
  43176. return;
  43177. }
  43178. if (deleteFrames) {
  43179. var from = range.from;
  43180. var to = range.to;
  43181. // this loop MUST go high to low for multiple splices to work
  43182. for (var key = this._keys.length - 1; key >= 0; key--) {
  43183. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  43184. this._keys.splice(key, 1);
  43185. }
  43186. }
  43187. }
  43188. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  43189. };
  43190. Animation.prototype.getRange = function (name) {
  43191. return this._ranges[name];
  43192. };
  43193. Animation.prototype.getKeys = function () {
  43194. return this._keys;
  43195. };
  43196. Animation.prototype.getHighestFrame = function () {
  43197. var ret = 0;
  43198. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  43199. if (ret < this._keys[key].frame) {
  43200. ret = this._keys[key].frame;
  43201. }
  43202. }
  43203. return ret;
  43204. };
  43205. Animation.prototype.getEasingFunction = function () {
  43206. return this._easingFunction;
  43207. };
  43208. Animation.prototype.setEasingFunction = function (easingFunction) {
  43209. this._easingFunction = easingFunction;
  43210. };
  43211. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  43212. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  43213. };
  43214. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43215. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43216. };
  43217. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  43218. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  43219. };
  43220. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43221. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  43222. };
  43223. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  43224. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  43225. };
  43226. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43227. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43228. };
  43229. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  43230. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  43231. };
  43232. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43233. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43234. };
  43235. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  43236. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  43237. };
  43238. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  43239. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  43240. };
  43241. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  43242. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  43243. };
  43244. Animation.prototype.clone = function () {
  43245. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  43246. clone.enableBlending = this.enableBlending;
  43247. clone.blendingSpeed = this.blendingSpeed;
  43248. if (this._keys) {
  43249. clone.setKeys(this._keys);
  43250. }
  43251. if (this._ranges) {
  43252. clone._ranges = {};
  43253. for (var name in this._ranges) {
  43254. var range = this._ranges[name];
  43255. if (!range) {
  43256. continue;
  43257. }
  43258. clone._ranges[name] = range.clone();
  43259. }
  43260. }
  43261. return clone;
  43262. };
  43263. Animation.prototype.setKeys = function (values) {
  43264. this._keys = values.slice(0);
  43265. };
  43266. Animation.prototype.serialize = function () {
  43267. var serializationObject = {};
  43268. serializationObject.name = this.name;
  43269. serializationObject.property = this.targetProperty;
  43270. serializationObject.framePerSecond = this.framePerSecond;
  43271. serializationObject.dataType = this.dataType;
  43272. serializationObject.loopBehavior = this.loopMode;
  43273. serializationObject.enableBlending = this.enableBlending;
  43274. serializationObject.blendingSpeed = this.blendingSpeed;
  43275. var dataType = this.dataType;
  43276. serializationObject.keys = [];
  43277. var keys = this.getKeys();
  43278. for (var index = 0; index < keys.length; index++) {
  43279. var animationKey = keys[index];
  43280. var key = {};
  43281. key.frame = animationKey.frame;
  43282. switch (dataType) {
  43283. case Animation.ANIMATIONTYPE_FLOAT:
  43284. key.values = [animationKey.value];
  43285. break;
  43286. case Animation.ANIMATIONTYPE_QUATERNION:
  43287. case Animation.ANIMATIONTYPE_MATRIX:
  43288. case Animation.ANIMATIONTYPE_VECTOR3:
  43289. case Animation.ANIMATIONTYPE_COLOR3:
  43290. key.values = animationKey.value.asArray();
  43291. break;
  43292. }
  43293. serializationObject.keys.push(key);
  43294. }
  43295. serializationObject.ranges = [];
  43296. for (var name in this._ranges) {
  43297. var source = this._ranges[name];
  43298. if (!source) {
  43299. continue;
  43300. }
  43301. var range = {};
  43302. range.name = name;
  43303. range.from = source.from;
  43304. range.to = source.to;
  43305. serializationObject.ranges.push(range);
  43306. }
  43307. return serializationObject;
  43308. };
  43309. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  43310. get: function () {
  43311. return Animation._ANIMATIONTYPE_FLOAT;
  43312. },
  43313. enumerable: true,
  43314. configurable: true
  43315. });
  43316. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  43317. get: function () {
  43318. return Animation._ANIMATIONTYPE_VECTOR3;
  43319. },
  43320. enumerable: true,
  43321. configurable: true
  43322. });
  43323. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  43324. get: function () {
  43325. return Animation._ANIMATIONTYPE_VECTOR2;
  43326. },
  43327. enumerable: true,
  43328. configurable: true
  43329. });
  43330. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  43331. get: function () {
  43332. return Animation._ANIMATIONTYPE_SIZE;
  43333. },
  43334. enumerable: true,
  43335. configurable: true
  43336. });
  43337. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  43338. get: function () {
  43339. return Animation._ANIMATIONTYPE_QUATERNION;
  43340. },
  43341. enumerable: true,
  43342. configurable: true
  43343. });
  43344. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  43345. get: function () {
  43346. return Animation._ANIMATIONTYPE_MATRIX;
  43347. },
  43348. enumerable: true,
  43349. configurable: true
  43350. });
  43351. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  43352. get: function () {
  43353. return Animation._ANIMATIONTYPE_COLOR3;
  43354. },
  43355. enumerable: true,
  43356. configurable: true
  43357. });
  43358. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  43359. get: function () {
  43360. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  43361. },
  43362. enumerable: true,
  43363. configurable: true
  43364. });
  43365. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  43366. get: function () {
  43367. return Animation._ANIMATIONLOOPMODE_CYCLE;
  43368. },
  43369. enumerable: true,
  43370. configurable: true
  43371. });
  43372. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  43373. get: function () {
  43374. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43375. },
  43376. enumerable: true,
  43377. configurable: true
  43378. });
  43379. Animation.Parse = function (parsedAnimation) {
  43380. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43381. var dataType = parsedAnimation.dataType;
  43382. var keys = [];
  43383. var data;
  43384. var index;
  43385. if (parsedAnimation.enableBlending) {
  43386. animation.enableBlending = parsedAnimation.enableBlending;
  43387. }
  43388. if (parsedAnimation.blendingSpeed) {
  43389. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43390. }
  43391. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43392. var key = parsedAnimation.keys[index];
  43393. var inTangent;
  43394. var outTangent;
  43395. switch (dataType) {
  43396. case Animation.ANIMATIONTYPE_FLOAT:
  43397. data = key.values[0];
  43398. if (key.values.length >= 1) {
  43399. inTangent = key.values[1];
  43400. }
  43401. if (key.values.length >= 2) {
  43402. outTangent = key.values[2];
  43403. }
  43404. break;
  43405. case Animation.ANIMATIONTYPE_QUATERNION:
  43406. data = BABYLON.Quaternion.FromArray(key.values);
  43407. if (key.values.length >= 8) {
  43408. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43409. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43410. inTangent = _inTangent;
  43411. }
  43412. }
  43413. if (key.values.length >= 12) {
  43414. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43415. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43416. outTangent = _outTangent;
  43417. }
  43418. }
  43419. break;
  43420. case Animation.ANIMATIONTYPE_MATRIX:
  43421. data = BABYLON.Matrix.FromArray(key.values);
  43422. break;
  43423. case Animation.ANIMATIONTYPE_COLOR3:
  43424. data = BABYLON.Color3.FromArray(key.values);
  43425. break;
  43426. case Animation.ANIMATIONTYPE_VECTOR3:
  43427. default:
  43428. data = BABYLON.Vector3.FromArray(key.values);
  43429. break;
  43430. }
  43431. var keyData = {};
  43432. keyData.frame = key.frame;
  43433. keyData.value = data;
  43434. if (inTangent != undefined) {
  43435. keyData.inTangent = inTangent;
  43436. }
  43437. if (outTangent != undefined) {
  43438. keyData.outTangent = outTangent;
  43439. }
  43440. keys.push(keyData);
  43441. }
  43442. animation.setKeys(keys);
  43443. if (parsedAnimation.ranges) {
  43444. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43445. data = parsedAnimation.ranges[index];
  43446. animation.createRange(data.name, data.from, data.to);
  43447. }
  43448. }
  43449. return animation;
  43450. };
  43451. Animation.AppendSerializedAnimations = function (source, destination) {
  43452. if (source.animations) {
  43453. destination.animations = [];
  43454. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43455. var animation = source.animations[animationIndex];
  43456. destination.animations.push(animation.serialize());
  43457. }
  43458. }
  43459. };
  43460. Animation.AllowMatricesInterpolation = false;
  43461. // Statics
  43462. Animation._ANIMATIONTYPE_FLOAT = 0;
  43463. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43464. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43465. Animation._ANIMATIONTYPE_MATRIX = 3;
  43466. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43467. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43468. Animation._ANIMATIONTYPE_SIZE = 6;
  43469. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43470. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43471. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43472. return Animation;
  43473. }());
  43474. BABYLON.Animation = Animation;
  43475. })(BABYLON || (BABYLON = {}));
  43476. //# sourceMappingURL=babylon.animation.js.map
  43477. var BABYLON;
  43478. (function (BABYLON) {
  43479. /**
  43480. * This class defines the direct association between an animation and a target
  43481. */
  43482. var TargetedAnimation = /** @class */ (function () {
  43483. function TargetedAnimation() {
  43484. }
  43485. return TargetedAnimation;
  43486. }());
  43487. BABYLON.TargetedAnimation = TargetedAnimation;
  43488. /**
  43489. * Use this class to create coordinated animations on multiple targets
  43490. */
  43491. var AnimationGroup = /** @class */ (function () {
  43492. function AnimationGroup(name, scene) {
  43493. if (scene === void 0) { scene = null; }
  43494. this.name = name;
  43495. this._targetedAnimations = new Array();
  43496. this._animatables = new Array();
  43497. this._from = Number.MAX_VALUE;
  43498. this._to = -Number.MAX_VALUE;
  43499. this._speedRatio = 1;
  43500. this.onAnimationEndObservable = new BABYLON.Observable();
  43501. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43502. this._scene.animationGroups.push(this);
  43503. }
  43504. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43505. /**
  43506. * Define if the animations are started
  43507. */
  43508. get: function () {
  43509. return this._isStarted;
  43510. },
  43511. enumerable: true,
  43512. configurable: true
  43513. });
  43514. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43515. /**
  43516. * Gets or sets the speed ratio to use for all animations
  43517. */
  43518. get: function () {
  43519. return this._speedRatio;
  43520. },
  43521. /**
  43522. * Gets or sets the speed ratio to use for all animations
  43523. */
  43524. set: function (value) {
  43525. if (this._speedRatio === value) {
  43526. return;
  43527. }
  43528. this._speedRatio = value;
  43529. for (var index = 0; index < this._animatables.length; index++) {
  43530. var animatable = this._animatables[index];
  43531. animatable.speedRatio = this._speedRatio;
  43532. }
  43533. },
  43534. enumerable: true,
  43535. configurable: true
  43536. });
  43537. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43538. /**
  43539. * Gets the targeted animations for this animation group
  43540. */
  43541. get: function () {
  43542. return this._targetedAnimations;
  43543. },
  43544. enumerable: true,
  43545. configurable: true
  43546. });
  43547. /**
  43548. * Add an animation (with its target) in the group
  43549. * @param animation defines the animation we want to add
  43550. * @param target defines the target of the animation
  43551. * @returns the {BABYLON.TargetedAnimation} object
  43552. */
  43553. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43554. var targetedAnimation = {
  43555. animation: animation,
  43556. target: target
  43557. };
  43558. var keys = animation.getKeys();
  43559. if (this._from > keys[0].frame) {
  43560. this._from = keys[0].frame;
  43561. }
  43562. if (this._to < keys[keys.length - 1].frame) {
  43563. this._to = keys[keys.length - 1].frame;
  43564. }
  43565. this._targetedAnimations.push(targetedAnimation);
  43566. return targetedAnimation;
  43567. };
  43568. /**
  43569. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43570. * It can add constant keys at begin or end
  43571. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43572. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43573. */
  43574. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43575. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43576. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43577. beginFrame = Math.max(beginFrame, this._from);
  43578. endFrame = Math.min(endFrame, this._to);
  43579. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43580. var targetedAnimation = this._targetedAnimations[index];
  43581. var keys = targetedAnimation.animation.getKeys();
  43582. var startKey = keys[0];
  43583. var endKey = keys[keys.length - 1];
  43584. if (startKey.frame > beginFrame) {
  43585. var newKey = {
  43586. frame: beginFrame,
  43587. value: startKey.value,
  43588. inTangent: startKey.inTangent,
  43589. outTangent: startKey.outTangent,
  43590. interpolation: startKey.interpolation
  43591. };
  43592. keys.splice(0, 0, newKey);
  43593. }
  43594. if (endKey.frame < endFrame) {
  43595. var newKey = {
  43596. frame: endFrame,
  43597. value: endKey.value,
  43598. inTangent: endKey.outTangent,
  43599. outTangent: endKey.outTangent,
  43600. interpolation: endKey.interpolation
  43601. };
  43602. keys.push(newKey);
  43603. }
  43604. }
  43605. return this;
  43606. };
  43607. /**
  43608. * Start all animations on given targets
  43609. * @param loop defines if animations must loop
  43610. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43611. */
  43612. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43613. var _this = this;
  43614. if (loop === void 0) { loop = false; }
  43615. if (speedRatio === void 0) { speedRatio = 1; }
  43616. if (this._isStarted || this._targetedAnimations.length === 0) {
  43617. return this;
  43618. }
  43619. var _loop_1 = function () {
  43620. var targetedAnimation = this_1._targetedAnimations[index];
  43621. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43622. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43623. }));
  43624. };
  43625. var this_1 = this;
  43626. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43627. _loop_1();
  43628. }
  43629. this._speedRatio = speedRatio;
  43630. this._isStarted = true;
  43631. return this;
  43632. };
  43633. /**
  43634. * Pause all animations
  43635. */
  43636. AnimationGroup.prototype.pause = function () {
  43637. if (!this._isStarted) {
  43638. return this;
  43639. }
  43640. for (var index = 0; index < this._animatables.length; index++) {
  43641. var animatable = this._animatables[index];
  43642. animatable.pause();
  43643. }
  43644. return this;
  43645. };
  43646. /**
  43647. * Play all animations to initial state
  43648. * This function will start() the animations if they were not started or will restart() them if they were paused
  43649. * @param loop defines if animations must loop
  43650. */
  43651. AnimationGroup.prototype.play = function (loop) {
  43652. if (this.isStarted) {
  43653. if (loop !== undefined) {
  43654. for (var index = 0; index < this._animatables.length; index++) {
  43655. var animatable = this._animatables[index];
  43656. animatable.loopAnimation = loop;
  43657. }
  43658. }
  43659. this.restart();
  43660. }
  43661. else {
  43662. this.start(loop, this._speedRatio);
  43663. }
  43664. return this;
  43665. };
  43666. /**
  43667. * Reset all animations to initial state
  43668. */
  43669. AnimationGroup.prototype.reset = function () {
  43670. if (!this._isStarted) {
  43671. return this;
  43672. }
  43673. for (var index = 0; index < this._animatables.length; index++) {
  43674. var animatable = this._animatables[index];
  43675. animatable.reset();
  43676. }
  43677. return this;
  43678. };
  43679. /**
  43680. * Restart animations from key 0
  43681. */
  43682. AnimationGroup.prototype.restart = function () {
  43683. if (!this._isStarted) {
  43684. return this;
  43685. }
  43686. for (var index = 0; index < this._animatables.length; index++) {
  43687. var animatable = this._animatables[index];
  43688. animatable.restart();
  43689. }
  43690. return this;
  43691. };
  43692. /**
  43693. * Stop all animations
  43694. */
  43695. AnimationGroup.prototype.stop = function () {
  43696. if (!this._isStarted) {
  43697. return this;
  43698. }
  43699. for (var index = 0; index < this._animatables.length; index++) {
  43700. var animatable = this._animatables[index];
  43701. animatable.stop();
  43702. }
  43703. this._isStarted = false;
  43704. return this;
  43705. };
  43706. /**
  43707. * Dispose all associated resources
  43708. */
  43709. AnimationGroup.prototype.dispose = function () {
  43710. this._targetedAnimations = [];
  43711. this._animatables = [];
  43712. var index = this._scene.animationGroups.indexOf(this);
  43713. if (index > -1) {
  43714. this._scene.animationGroups.splice(index, 1);
  43715. }
  43716. };
  43717. return AnimationGroup;
  43718. }());
  43719. BABYLON.AnimationGroup = AnimationGroup;
  43720. })(BABYLON || (BABYLON = {}));
  43721. //# sourceMappingURL=babylon.animationGroup.js.map
  43722. var BABYLON;
  43723. (function (BABYLON) {
  43724. var RuntimeAnimation = /** @class */ (function () {
  43725. function RuntimeAnimation(target, animation) {
  43726. this._offsetsCache = {};
  43727. this._highLimitsCache = {};
  43728. this._stopped = false;
  43729. this._blendingFactor = 0;
  43730. this._ratioOffset = 0;
  43731. this._animation = animation;
  43732. this._target = target;
  43733. animation._runtimeAnimations.push(this);
  43734. }
  43735. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  43736. get: function () {
  43737. return this._animation;
  43738. },
  43739. enumerable: true,
  43740. configurable: true
  43741. });
  43742. RuntimeAnimation.prototype.reset = function () {
  43743. this._offsetsCache = {};
  43744. this._highLimitsCache = {};
  43745. this.currentFrame = 0;
  43746. this._blendingFactor = 0;
  43747. this._originalBlendValue = null;
  43748. };
  43749. RuntimeAnimation.prototype.isStopped = function () {
  43750. return this._stopped;
  43751. };
  43752. RuntimeAnimation.prototype.dispose = function () {
  43753. var index = this._animation.runtimeAnimations.indexOf(this);
  43754. if (index > -1) {
  43755. this._animation.runtimeAnimations.splice(index, 1);
  43756. }
  43757. };
  43758. RuntimeAnimation.prototype._getKeyValue = function (value) {
  43759. if (typeof value === "function") {
  43760. return value();
  43761. }
  43762. return value;
  43763. };
  43764. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  43765. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  43766. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  43767. }
  43768. this.currentFrame = currentFrame;
  43769. var keys = this._animation.getKeys();
  43770. // Try to get a hash to find the right key
  43771. 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));
  43772. if (keys[startKeyIndex].frame >= currentFrame) {
  43773. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  43774. startKeyIndex--;
  43775. }
  43776. }
  43777. for (var key = startKeyIndex; key < keys.length; key++) {
  43778. var endKey = keys[key + 1];
  43779. if (endKey.frame >= currentFrame) {
  43780. var startKey = keys[key];
  43781. var startValue = this._getKeyValue(startKey.value);
  43782. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  43783. return startValue;
  43784. }
  43785. var endValue = this._getKeyValue(endKey.value);
  43786. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  43787. var frameDelta = endKey.frame - startKey.frame;
  43788. // gradient : percent of currentFrame between the frame inf and the frame sup
  43789. var gradient = (currentFrame - startKey.frame) / frameDelta;
  43790. // check for easingFunction and correction of gradient
  43791. var easingFunction = this._animation.getEasingFunction();
  43792. if (easingFunction != null) {
  43793. gradient = easingFunction.ease(gradient);
  43794. }
  43795. switch (this._animation.dataType) {
  43796. // Float
  43797. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43798. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  43799. switch (loopMode) {
  43800. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43801. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43802. return floatValue;
  43803. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43804. return offsetValue * repeatCount + floatValue;
  43805. }
  43806. break;
  43807. // Quaternion
  43808. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43809. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  43810. switch (loopMode) {
  43811. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43812. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43813. return quatValue;
  43814. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43815. return quatValue.add(offsetValue.scale(repeatCount));
  43816. }
  43817. return quatValue;
  43818. // Vector3
  43819. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43820. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  43821. switch (loopMode) {
  43822. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43823. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43824. return vec3Value;
  43825. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43826. return vec3Value.add(offsetValue.scale(repeatCount));
  43827. }
  43828. // Vector2
  43829. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43830. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  43831. switch (loopMode) {
  43832. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43833. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43834. return vec2Value;
  43835. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43836. return vec2Value.add(offsetValue.scale(repeatCount));
  43837. }
  43838. // Size
  43839. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43840. switch (loopMode) {
  43841. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43842. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43843. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  43844. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43845. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43846. }
  43847. // Color3
  43848. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43849. switch (loopMode) {
  43850. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43851. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43852. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  43853. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43854. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43855. }
  43856. // Matrix
  43857. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  43858. switch (loopMode) {
  43859. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43860. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43861. if (BABYLON.Animation.AllowMatricesInterpolation) {
  43862. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  43863. }
  43864. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43865. return startValue;
  43866. }
  43867. default:
  43868. break;
  43869. }
  43870. break;
  43871. }
  43872. }
  43873. return this._getKeyValue(keys[keys.length - 1].value);
  43874. };
  43875. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  43876. if (blend === void 0) { blend = false; }
  43877. // Set value
  43878. var path;
  43879. var destination;
  43880. var targetPropertyPath = this._animation.targetPropertyPath;
  43881. if (targetPropertyPath.length > 1) {
  43882. var property = this._target[targetPropertyPath[0]];
  43883. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  43884. property = property[targetPropertyPath[index]];
  43885. }
  43886. path = targetPropertyPath[targetPropertyPath.length - 1];
  43887. destination = property;
  43888. }
  43889. else {
  43890. path = targetPropertyPath[0];
  43891. destination = this._target;
  43892. }
  43893. // Blending
  43894. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  43895. if (!this._originalBlendValue) {
  43896. if (destination[path].clone) {
  43897. this._originalBlendValue = destination[path].clone();
  43898. }
  43899. else {
  43900. this._originalBlendValue = destination[path];
  43901. }
  43902. }
  43903. if (this._originalBlendValue.prototype) {
  43904. if (this._originalBlendValue.prototype.Lerp) {
  43905. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  43906. }
  43907. else {
  43908. destination[path] = currentValue;
  43909. }
  43910. }
  43911. else if (this._originalBlendValue.m) {
  43912. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  43913. }
  43914. else {
  43915. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  43916. }
  43917. this._blendingFactor += this._animation.blendingSpeed;
  43918. }
  43919. else {
  43920. destination[path] = currentValue;
  43921. }
  43922. if (this._target.markAsDirty) {
  43923. this._target.markAsDirty(this._animation.targetProperty);
  43924. }
  43925. };
  43926. RuntimeAnimation.prototype.goToFrame = function (frame) {
  43927. var keys = this._animation.getKeys();
  43928. if (frame < keys[0].frame) {
  43929. frame = keys[0].frame;
  43930. }
  43931. else if (frame > keys[keys.length - 1].frame) {
  43932. frame = keys[keys.length - 1].frame;
  43933. }
  43934. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  43935. this.setValue(currentValue);
  43936. };
  43937. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  43938. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  43939. this._ratioOffset = this._previousRatio - newRatio;
  43940. };
  43941. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  43942. if (blend === void 0) { blend = false; }
  43943. var targetPropertyPath = this._animation.targetPropertyPath;
  43944. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  43945. this._stopped = true;
  43946. return false;
  43947. }
  43948. var returnValue = true;
  43949. var keys = this._animation.getKeys();
  43950. // Adding a start key at frame 0 if missing
  43951. if (keys[0].frame !== 0) {
  43952. var newKey = { frame: 0, value: keys[0].value };
  43953. keys.splice(0, 0, newKey);
  43954. }
  43955. // Check limits
  43956. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  43957. from = keys[0].frame;
  43958. }
  43959. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  43960. to = keys[keys.length - 1].frame;
  43961. }
  43962. //to and from cannot be the same key
  43963. if (from === to) {
  43964. if (from > keys[0].frame) {
  43965. from--;
  43966. }
  43967. else if (to < keys[keys.length - 1].frame) {
  43968. to++;
  43969. }
  43970. }
  43971. // Compute ratio
  43972. var range = to - from;
  43973. var offsetValue;
  43974. // ratio represents the frame delta between from and to
  43975. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  43976. var highLimitValue = 0;
  43977. this._previousDelay = delay;
  43978. this._previousRatio = ratio;
  43979. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  43980. returnValue = false;
  43981. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  43982. }
  43983. else {
  43984. // Get max value if required
  43985. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  43986. var keyOffset = to.toString() + from.toString();
  43987. if (!this._offsetsCache[keyOffset]) {
  43988. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43989. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43990. switch (this._animation.dataType) {
  43991. // Float
  43992. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43993. this._offsetsCache[keyOffset] = toValue - fromValue;
  43994. break;
  43995. // Quaternion
  43996. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43997. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43998. break;
  43999. // Vector3
  44000. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44001. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44002. // Vector2
  44003. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44004. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44005. // Size
  44006. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44007. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44008. // Color3
  44009. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44010. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44011. default:
  44012. break;
  44013. }
  44014. this._highLimitsCache[keyOffset] = toValue;
  44015. }
  44016. highLimitValue = this._highLimitsCache[keyOffset];
  44017. offsetValue = this._offsetsCache[keyOffset];
  44018. }
  44019. }
  44020. if (offsetValue === undefined) {
  44021. switch (this._animation.dataType) {
  44022. // Float
  44023. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44024. offsetValue = 0;
  44025. break;
  44026. // Quaternion
  44027. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44028. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44029. break;
  44030. // Vector3
  44031. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44032. offsetValue = BABYLON.Vector3.Zero();
  44033. break;
  44034. // Vector2
  44035. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44036. offsetValue = BABYLON.Vector2.Zero();
  44037. break;
  44038. // Size
  44039. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44040. offsetValue = BABYLON.Size.Zero();
  44041. break;
  44042. // Color3
  44043. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44044. offsetValue = BABYLON.Color3.Black();
  44045. }
  44046. }
  44047. // Compute value
  44048. var repeatCount = (ratio / range) >> 0;
  44049. var currentFrame = returnValue ? from + ratio % range : to;
  44050. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44051. // Set value
  44052. this.setValue(currentValue);
  44053. // Check events
  44054. var events = this._animation.getEvents();
  44055. for (var index = 0; index < events.length; index++) {
  44056. // Make sure current frame has passed event frame and that event frame is within the current range
  44057. // Also, handle both forward and reverse animations
  44058. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44059. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44060. var event = events[index];
  44061. if (!event.isDone) {
  44062. // If event should be done only once, remove it.
  44063. if (event.onlyOnce) {
  44064. events.splice(index, 1);
  44065. index--;
  44066. }
  44067. event.isDone = true;
  44068. event.action();
  44069. } // Don't do anything if the event has already be done.
  44070. }
  44071. else if (events[index].isDone && !events[index].onlyOnce) {
  44072. // reset event, the animation is looping
  44073. events[index].isDone = false;
  44074. }
  44075. }
  44076. if (!returnValue) {
  44077. this._stopped = true;
  44078. }
  44079. return returnValue;
  44080. };
  44081. return RuntimeAnimation;
  44082. }());
  44083. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44084. })(BABYLON || (BABYLON = {}));
  44085. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44086. var BABYLON;
  44087. (function (BABYLON) {
  44088. var Animatable = /** @class */ (function () {
  44089. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44090. if (fromFrame === void 0) { fromFrame = 0; }
  44091. if (toFrame === void 0) { toFrame = 100; }
  44092. if (loopAnimation === void 0) { loopAnimation = false; }
  44093. if (speedRatio === void 0) { speedRatio = 1.0; }
  44094. this.target = target;
  44095. this.fromFrame = fromFrame;
  44096. this.toFrame = toFrame;
  44097. this.loopAnimation = loopAnimation;
  44098. this.onAnimationEnd = onAnimationEnd;
  44099. this._localDelayOffset = null;
  44100. this._pausedDelay = null;
  44101. this._runtimeAnimations = new Array();
  44102. this._paused = false;
  44103. this._speedRatio = 1;
  44104. this.animationStarted = false;
  44105. if (animations) {
  44106. this.appendAnimations(target, animations);
  44107. }
  44108. this._speedRatio = speedRatio;
  44109. this._scene = scene;
  44110. scene._activeAnimatables.push(this);
  44111. }
  44112. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44113. get: function () {
  44114. return this._speedRatio;
  44115. },
  44116. set: function (value) {
  44117. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44118. var animation = this._runtimeAnimations[index];
  44119. animation._prepareForSpeedRatioChange(value);
  44120. }
  44121. this._speedRatio = value;
  44122. },
  44123. enumerable: true,
  44124. configurable: true
  44125. });
  44126. // Methods
  44127. Animatable.prototype.getAnimations = function () {
  44128. return this._runtimeAnimations;
  44129. };
  44130. Animatable.prototype.appendAnimations = function (target, animations) {
  44131. for (var index = 0; index < animations.length; index++) {
  44132. var animation = animations[index];
  44133. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  44134. }
  44135. };
  44136. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  44137. var runtimeAnimations = this._runtimeAnimations;
  44138. for (var index = 0; index < runtimeAnimations.length; index++) {
  44139. if (runtimeAnimations[index].animation.targetProperty === property) {
  44140. return runtimeAnimations[index].animation;
  44141. }
  44142. }
  44143. return null;
  44144. };
  44145. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  44146. var runtimeAnimations = this._runtimeAnimations;
  44147. for (var index = 0; index < runtimeAnimations.length; index++) {
  44148. if (runtimeAnimations[index].animation.targetProperty === property) {
  44149. return runtimeAnimations[index];
  44150. }
  44151. }
  44152. return null;
  44153. };
  44154. Animatable.prototype.reset = function () {
  44155. var runtimeAnimations = this._runtimeAnimations;
  44156. for (var index = 0; index < runtimeAnimations.length; index++) {
  44157. runtimeAnimations[index].reset();
  44158. }
  44159. // Reset to original value
  44160. for (index = 0; index < runtimeAnimations.length; index++) {
  44161. var animation = runtimeAnimations[index];
  44162. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  44163. }
  44164. this._localDelayOffset = null;
  44165. this._pausedDelay = null;
  44166. };
  44167. Animatable.prototype.enableBlending = function (blendingSpeed) {
  44168. var runtimeAnimations = this._runtimeAnimations;
  44169. for (var index = 0; index < runtimeAnimations.length; index++) {
  44170. runtimeAnimations[index].animation.enableBlending = true;
  44171. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  44172. }
  44173. };
  44174. Animatable.prototype.disableBlending = function () {
  44175. var runtimeAnimations = this._runtimeAnimations;
  44176. for (var index = 0; index < runtimeAnimations.length; index++) {
  44177. runtimeAnimations[index].animation.enableBlending = false;
  44178. }
  44179. };
  44180. Animatable.prototype.goToFrame = function (frame) {
  44181. var runtimeAnimations = this._runtimeAnimations;
  44182. if (runtimeAnimations[0]) {
  44183. var fps = runtimeAnimations[0].animation.framePerSecond;
  44184. var currentFrame = runtimeAnimations[0].currentFrame;
  44185. var adjustTime = frame - currentFrame;
  44186. var delay = adjustTime * 1000 / fps;
  44187. if (this._localDelayOffset === null) {
  44188. this._localDelayOffset = 0;
  44189. }
  44190. this._localDelayOffset -= delay;
  44191. }
  44192. for (var index = 0; index < runtimeAnimations.length; index++) {
  44193. runtimeAnimations[index].goToFrame(frame);
  44194. }
  44195. };
  44196. Animatable.prototype.pause = function () {
  44197. if (this._paused) {
  44198. return;
  44199. }
  44200. this._paused = true;
  44201. };
  44202. Animatable.prototype.restart = function () {
  44203. this._paused = false;
  44204. };
  44205. Animatable.prototype.stop = function (animationName) {
  44206. if (animationName) {
  44207. var idx = this._scene._activeAnimatables.indexOf(this);
  44208. if (idx > -1) {
  44209. var runtimeAnimations = this._runtimeAnimations;
  44210. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  44211. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  44212. continue;
  44213. }
  44214. runtimeAnimations[index].dispose();
  44215. runtimeAnimations.splice(index, 1);
  44216. }
  44217. if (runtimeAnimations.length == 0) {
  44218. this._scene._activeAnimatables.splice(idx, 1);
  44219. if (this.onAnimationEnd) {
  44220. this.onAnimationEnd();
  44221. }
  44222. }
  44223. }
  44224. }
  44225. else {
  44226. var index = this._scene._activeAnimatables.indexOf(this);
  44227. if (index > -1) {
  44228. this._scene._activeAnimatables.splice(index, 1);
  44229. var runtimeAnimations = this._runtimeAnimations;
  44230. for (var index = 0; index < runtimeAnimations.length; index++) {
  44231. runtimeAnimations[index].dispose();
  44232. }
  44233. if (this.onAnimationEnd) {
  44234. this.onAnimationEnd();
  44235. }
  44236. }
  44237. }
  44238. };
  44239. Animatable.prototype._animate = function (delay) {
  44240. if (this._paused) {
  44241. this.animationStarted = false;
  44242. if (this._pausedDelay === null) {
  44243. this._pausedDelay = delay;
  44244. }
  44245. return true;
  44246. }
  44247. if (this._localDelayOffset === null) {
  44248. this._localDelayOffset = delay;
  44249. }
  44250. else if (this._pausedDelay !== null) {
  44251. this._localDelayOffset += delay - this._pausedDelay;
  44252. this._pausedDelay = null;
  44253. }
  44254. // Animating
  44255. var running = false;
  44256. var runtimeAnimations = this._runtimeAnimations;
  44257. var index;
  44258. for (index = 0; index < runtimeAnimations.length; index++) {
  44259. var animation = runtimeAnimations[index];
  44260. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  44261. running = running || isRunning;
  44262. }
  44263. this.animationStarted = running;
  44264. if (!running) {
  44265. // Remove from active animatables
  44266. index = this._scene._activeAnimatables.indexOf(this);
  44267. this._scene._activeAnimatables.splice(index, 1);
  44268. // Dispose all runtime animations
  44269. for (index = 0; index < runtimeAnimations.length; index++) {
  44270. runtimeAnimations[index].dispose();
  44271. }
  44272. }
  44273. if (!running && this.onAnimationEnd) {
  44274. this.onAnimationEnd();
  44275. this.onAnimationEnd = null;
  44276. }
  44277. return running;
  44278. };
  44279. return Animatable;
  44280. }());
  44281. BABYLON.Animatable = Animatable;
  44282. })(BABYLON || (BABYLON = {}));
  44283. //# sourceMappingURL=babylon.animatable.js.map
  44284. var BABYLON;
  44285. (function (BABYLON) {
  44286. var EasingFunction = /** @class */ (function () {
  44287. function EasingFunction() {
  44288. // Properties
  44289. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  44290. }
  44291. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  44292. get: function () {
  44293. return EasingFunction._EASINGMODE_EASEIN;
  44294. },
  44295. enumerable: true,
  44296. configurable: true
  44297. });
  44298. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  44299. get: function () {
  44300. return EasingFunction._EASINGMODE_EASEOUT;
  44301. },
  44302. enumerable: true,
  44303. configurable: true
  44304. });
  44305. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  44306. get: function () {
  44307. return EasingFunction._EASINGMODE_EASEINOUT;
  44308. },
  44309. enumerable: true,
  44310. configurable: true
  44311. });
  44312. EasingFunction.prototype.setEasingMode = function (easingMode) {
  44313. var n = Math.min(Math.max(easingMode, 0), 2);
  44314. this._easingMode = n;
  44315. };
  44316. EasingFunction.prototype.getEasingMode = function () {
  44317. return this._easingMode;
  44318. };
  44319. EasingFunction.prototype.easeInCore = function (gradient) {
  44320. throw new Error('You must implement this method');
  44321. };
  44322. EasingFunction.prototype.ease = function (gradient) {
  44323. switch (this._easingMode) {
  44324. case EasingFunction.EASINGMODE_EASEIN:
  44325. return this.easeInCore(gradient);
  44326. case EasingFunction.EASINGMODE_EASEOUT:
  44327. return (1 - this.easeInCore(1 - gradient));
  44328. }
  44329. if (gradient >= 0.5) {
  44330. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  44331. }
  44332. return (this.easeInCore(gradient * 2) * 0.5);
  44333. };
  44334. //Statics
  44335. EasingFunction._EASINGMODE_EASEIN = 0;
  44336. EasingFunction._EASINGMODE_EASEOUT = 1;
  44337. EasingFunction._EASINGMODE_EASEINOUT = 2;
  44338. return EasingFunction;
  44339. }());
  44340. BABYLON.EasingFunction = EasingFunction;
  44341. var CircleEase = /** @class */ (function (_super) {
  44342. __extends(CircleEase, _super);
  44343. function CircleEase() {
  44344. return _super !== null && _super.apply(this, arguments) || this;
  44345. }
  44346. CircleEase.prototype.easeInCore = function (gradient) {
  44347. gradient = Math.max(0, Math.min(1, gradient));
  44348. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  44349. };
  44350. return CircleEase;
  44351. }(EasingFunction));
  44352. BABYLON.CircleEase = CircleEase;
  44353. var BackEase = /** @class */ (function (_super) {
  44354. __extends(BackEase, _super);
  44355. function BackEase(amplitude) {
  44356. if (amplitude === void 0) { amplitude = 1; }
  44357. var _this = _super.call(this) || this;
  44358. _this.amplitude = amplitude;
  44359. return _this;
  44360. }
  44361. BackEase.prototype.easeInCore = function (gradient) {
  44362. var num = Math.max(0, this.amplitude);
  44363. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  44364. };
  44365. return BackEase;
  44366. }(EasingFunction));
  44367. BABYLON.BackEase = BackEase;
  44368. var BounceEase = /** @class */ (function (_super) {
  44369. __extends(BounceEase, _super);
  44370. function BounceEase(bounces, bounciness) {
  44371. if (bounces === void 0) { bounces = 3; }
  44372. if (bounciness === void 0) { bounciness = 2; }
  44373. var _this = _super.call(this) || this;
  44374. _this.bounces = bounces;
  44375. _this.bounciness = bounciness;
  44376. return _this;
  44377. }
  44378. BounceEase.prototype.easeInCore = function (gradient) {
  44379. var y = Math.max(0.0, this.bounces);
  44380. var bounciness = this.bounciness;
  44381. if (bounciness <= 1.0) {
  44382. bounciness = 1.001;
  44383. }
  44384. var num9 = Math.pow(bounciness, y);
  44385. var num5 = 1.0 - bounciness;
  44386. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44387. var num15 = gradient * num4;
  44388. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44389. var num3 = Math.floor(num65);
  44390. var num13 = num3 + 1.0;
  44391. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44392. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44393. var num7 = (num8 + num12) * 0.5;
  44394. var num6 = gradient - num7;
  44395. var num2 = num7 - num8;
  44396. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44397. };
  44398. return BounceEase;
  44399. }(EasingFunction));
  44400. BABYLON.BounceEase = BounceEase;
  44401. var CubicEase = /** @class */ (function (_super) {
  44402. __extends(CubicEase, _super);
  44403. function CubicEase() {
  44404. return _super !== null && _super.apply(this, arguments) || this;
  44405. }
  44406. CubicEase.prototype.easeInCore = function (gradient) {
  44407. return (gradient * gradient * gradient);
  44408. };
  44409. return CubicEase;
  44410. }(EasingFunction));
  44411. BABYLON.CubicEase = CubicEase;
  44412. var ElasticEase = /** @class */ (function (_super) {
  44413. __extends(ElasticEase, _super);
  44414. function ElasticEase(oscillations, springiness) {
  44415. if (oscillations === void 0) { oscillations = 3; }
  44416. if (springiness === void 0) { springiness = 3; }
  44417. var _this = _super.call(this) || this;
  44418. _this.oscillations = oscillations;
  44419. _this.springiness = springiness;
  44420. return _this;
  44421. }
  44422. ElasticEase.prototype.easeInCore = function (gradient) {
  44423. var num2;
  44424. var num3 = Math.max(0.0, this.oscillations);
  44425. var num = Math.max(0.0, this.springiness);
  44426. if (num == 0) {
  44427. num2 = gradient;
  44428. }
  44429. else {
  44430. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44431. }
  44432. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44433. };
  44434. return ElasticEase;
  44435. }(EasingFunction));
  44436. BABYLON.ElasticEase = ElasticEase;
  44437. var ExponentialEase = /** @class */ (function (_super) {
  44438. __extends(ExponentialEase, _super);
  44439. function ExponentialEase(exponent) {
  44440. if (exponent === void 0) { exponent = 2; }
  44441. var _this = _super.call(this) || this;
  44442. _this.exponent = exponent;
  44443. return _this;
  44444. }
  44445. ExponentialEase.prototype.easeInCore = function (gradient) {
  44446. if (this.exponent <= 0) {
  44447. return gradient;
  44448. }
  44449. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44450. };
  44451. return ExponentialEase;
  44452. }(EasingFunction));
  44453. BABYLON.ExponentialEase = ExponentialEase;
  44454. var PowerEase = /** @class */ (function (_super) {
  44455. __extends(PowerEase, _super);
  44456. function PowerEase(power) {
  44457. if (power === void 0) { power = 2; }
  44458. var _this = _super.call(this) || this;
  44459. _this.power = power;
  44460. return _this;
  44461. }
  44462. PowerEase.prototype.easeInCore = function (gradient) {
  44463. var y = Math.max(0.0, this.power);
  44464. return Math.pow(gradient, y);
  44465. };
  44466. return PowerEase;
  44467. }(EasingFunction));
  44468. BABYLON.PowerEase = PowerEase;
  44469. var QuadraticEase = /** @class */ (function (_super) {
  44470. __extends(QuadraticEase, _super);
  44471. function QuadraticEase() {
  44472. return _super !== null && _super.apply(this, arguments) || this;
  44473. }
  44474. QuadraticEase.prototype.easeInCore = function (gradient) {
  44475. return (gradient * gradient);
  44476. };
  44477. return QuadraticEase;
  44478. }(EasingFunction));
  44479. BABYLON.QuadraticEase = QuadraticEase;
  44480. var QuarticEase = /** @class */ (function (_super) {
  44481. __extends(QuarticEase, _super);
  44482. function QuarticEase() {
  44483. return _super !== null && _super.apply(this, arguments) || this;
  44484. }
  44485. QuarticEase.prototype.easeInCore = function (gradient) {
  44486. return (gradient * gradient * gradient * gradient);
  44487. };
  44488. return QuarticEase;
  44489. }(EasingFunction));
  44490. BABYLON.QuarticEase = QuarticEase;
  44491. var QuinticEase = /** @class */ (function (_super) {
  44492. __extends(QuinticEase, _super);
  44493. function QuinticEase() {
  44494. return _super !== null && _super.apply(this, arguments) || this;
  44495. }
  44496. QuinticEase.prototype.easeInCore = function (gradient) {
  44497. return (gradient * gradient * gradient * gradient * gradient);
  44498. };
  44499. return QuinticEase;
  44500. }(EasingFunction));
  44501. BABYLON.QuinticEase = QuinticEase;
  44502. var SineEase = /** @class */ (function (_super) {
  44503. __extends(SineEase, _super);
  44504. function SineEase() {
  44505. return _super !== null && _super.apply(this, arguments) || this;
  44506. }
  44507. SineEase.prototype.easeInCore = function (gradient) {
  44508. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44509. };
  44510. return SineEase;
  44511. }(EasingFunction));
  44512. BABYLON.SineEase = SineEase;
  44513. var BezierCurveEase = /** @class */ (function (_super) {
  44514. __extends(BezierCurveEase, _super);
  44515. function BezierCurveEase(x1, y1, x2, y2) {
  44516. if (x1 === void 0) { x1 = 0; }
  44517. if (y1 === void 0) { y1 = 0; }
  44518. if (x2 === void 0) { x2 = 1; }
  44519. if (y2 === void 0) { y2 = 1; }
  44520. var _this = _super.call(this) || this;
  44521. _this.x1 = x1;
  44522. _this.y1 = y1;
  44523. _this.x2 = x2;
  44524. _this.y2 = y2;
  44525. return _this;
  44526. }
  44527. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44528. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44529. };
  44530. return BezierCurveEase;
  44531. }(EasingFunction));
  44532. BABYLON.BezierCurveEase = BezierCurveEase;
  44533. })(BABYLON || (BABYLON = {}));
  44534. //# sourceMappingURL=babylon.easing.js.map
  44535. var BABYLON;
  44536. (function (BABYLON) {
  44537. var Condition = /** @class */ (function () {
  44538. function Condition(actionManager) {
  44539. this._actionManager = actionManager;
  44540. }
  44541. Condition.prototype.isValid = function () {
  44542. return true;
  44543. };
  44544. Condition.prototype._getProperty = function (propertyPath) {
  44545. return this._actionManager._getProperty(propertyPath);
  44546. };
  44547. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44548. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44549. };
  44550. Condition.prototype.serialize = function () {
  44551. };
  44552. Condition.prototype._serialize = function (serializedCondition) {
  44553. return {
  44554. type: 2,
  44555. children: [],
  44556. name: serializedCondition.name,
  44557. properties: serializedCondition.properties
  44558. };
  44559. };
  44560. return Condition;
  44561. }());
  44562. BABYLON.Condition = Condition;
  44563. var ValueCondition = /** @class */ (function (_super) {
  44564. __extends(ValueCondition, _super);
  44565. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44566. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44567. var _this = _super.call(this, actionManager) || this;
  44568. _this.propertyPath = propertyPath;
  44569. _this.value = value;
  44570. _this.operator = operator;
  44571. _this._target = target;
  44572. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44573. _this._property = _this._getProperty(_this.propertyPath);
  44574. return _this;
  44575. }
  44576. Object.defineProperty(ValueCondition, "IsEqual", {
  44577. get: function () {
  44578. return ValueCondition._IsEqual;
  44579. },
  44580. enumerable: true,
  44581. configurable: true
  44582. });
  44583. Object.defineProperty(ValueCondition, "IsDifferent", {
  44584. get: function () {
  44585. return ValueCondition._IsDifferent;
  44586. },
  44587. enumerable: true,
  44588. configurable: true
  44589. });
  44590. Object.defineProperty(ValueCondition, "IsGreater", {
  44591. get: function () {
  44592. return ValueCondition._IsGreater;
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(ValueCondition, "IsLesser", {
  44598. get: function () {
  44599. return ValueCondition._IsLesser;
  44600. },
  44601. enumerable: true,
  44602. configurable: true
  44603. });
  44604. // Methods
  44605. ValueCondition.prototype.isValid = function () {
  44606. switch (this.operator) {
  44607. case ValueCondition.IsGreater:
  44608. return this._effectiveTarget[this._property] > this.value;
  44609. case ValueCondition.IsLesser:
  44610. return this._effectiveTarget[this._property] < this.value;
  44611. case ValueCondition.IsEqual:
  44612. case ValueCondition.IsDifferent:
  44613. var check;
  44614. if (this.value.equals) {
  44615. check = this.value.equals(this._effectiveTarget[this._property]);
  44616. }
  44617. else {
  44618. check = this.value === this._effectiveTarget[this._property];
  44619. }
  44620. return this.operator === ValueCondition.IsEqual ? check : !check;
  44621. }
  44622. return false;
  44623. };
  44624. ValueCondition.prototype.serialize = function () {
  44625. return this._serialize({
  44626. name: "ValueCondition",
  44627. properties: [
  44628. BABYLON.Action._GetTargetProperty(this._target),
  44629. { name: "propertyPath", value: this.propertyPath },
  44630. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44631. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44632. ]
  44633. });
  44634. };
  44635. ValueCondition.GetOperatorName = function (operator) {
  44636. switch (operator) {
  44637. case ValueCondition._IsEqual: return "IsEqual";
  44638. case ValueCondition._IsDifferent: return "IsDifferent";
  44639. case ValueCondition._IsGreater: return "IsGreater";
  44640. case ValueCondition._IsLesser: return "IsLesser";
  44641. default: return "";
  44642. }
  44643. };
  44644. // Statics
  44645. ValueCondition._IsEqual = 0;
  44646. ValueCondition._IsDifferent = 1;
  44647. ValueCondition._IsGreater = 2;
  44648. ValueCondition._IsLesser = 3;
  44649. return ValueCondition;
  44650. }(Condition));
  44651. BABYLON.ValueCondition = ValueCondition;
  44652. var PredicateCondition = /** @class */ (function (_super) {
  44653. __extends(PredicateCondition, _super);
  44654. function PredicateCondition(actionManager, predicate) {
  44655. var _this = _super.call(this, actionManager) || this;
  44656. _this.predicate = predicate;
  44657. return _this;
  44658. }
  44659. PredicateCondition.prototype.isValid = function () {
  44660. return this.predicate();
  44661. };
  44662. return PredicateCondition;
  44663. }(Condition));
  44664. BABYLON.PredicateCondition = PredicateCondition;
  44665. var StateCondition = /** @class */ (function (_super) {
  44666. __extends(StateCondition, _super);
  44667. function StateCondition(actionManager, target, value) {
  44668. var _this = _super.call(this, actionManager) || this;
  44669. _this.value = value;
  44670. _this._target = target;
  44671. return _this;
  44672. }
  44673. // Methods
  44674. StateCondition.prototype.isValid = function () {
  44675. return this._target.state === this.value;
  44676. };
  44677. StateCondition.prototype.serialize = function () {
  44678. return this._serialize({
  44679. name: "StateCondition",
  44680. properties: [
  44681. BABYLON.Action._GetTargetProperty(this._target),
  44682. { name: "value", value: this.value }
  44683. ]
  44684. });
  44685. };
  44686. return StateCondition;
  44687. }(Condition));
  44688. BABYLON.StateCondition = StateCondition;
  44689. })(BABYLON || (BABYLON = {}));
  44690. //# sourceMappingURL=babylon.condition.js.map
  44691. var BABYLON;
  44692. (function (BABYLON) {
  44693. var Action = /** @class */ (function () {
  44694. function Action(triggerOptions, condition) {
  44695. this.triggerOptions = triggerOptions;
  44696. this.onBeforeExecuteObservable = new BABYLON.Observable();
  44697. if (triggerOptions.parameter) {
  44698. this.trigger = triggerOptions.trigger;
  44699. this._triggerParameter = triggerOptions.parameter;
  44700. }
  44701. else {
  44702. this.trigger = triggerOptions;
  44703. }
  44704. this._nextActiveAction = this;
  44705. this._condition = condition;
  44706. }
  44707. // Methods
  44708. Action.prototype._prepare = function () {
  44709. };
  44710. Action.prototype.getTriggerParameter = function () {
  44711. return this._triggerParameter;
  44712. };
  44713. Action.prototype._executeCurrent = function (evt) {
  44714. if (this._nextActiveAction._condition) {
  44715. var condition = this._nextActiveAction._condition;
  44716. var currentRenderId = this._actionManager.getScene().getRenderId();
  44717. // We cache the current evaluation for the current frame
  44718. if (condition._evaluationId === currentRenderId) {
  44719. if (!condition._currentResult) {
  44720. return;
  44721. }
  44722. }
  44723. else {
  44724. condition._evaluationId = currentRenderId;
  44725. if (!condition.isValid()) {
  44726. condition._currentResult = false;
  44727. return;
  44728. }
  44729. condition._currentResult = true;
  44730. }
  44731. }
  44732. this.onBeforeExecuteObservable.notifyObservers(this);
  44733. this._nextActiveAction.execute(evt);
  44734. this.skipToNextActiveAction();
  44735. };
  44736. Action.prototype.execute = function (evt) {
  44737. };
  44738. Action.prototype.skipToNextActiveAction = function () {
  44739. if (this._nextActiveAction._child) {
  44740. if (!this._nextActiveAction._child._actionManager) {
  44741. this._nextActiveAction._child._actionManager = this._actionManager;
  44742. }
  44743. this._nextActiveAction = this._nextActiveAction._child;
  44744. }
  44745. else {
  44746. this._nextActiveAction = this;
  44747. }
  44748. };
  44749. Action.prototype.then = function (action) {
  44750. this._child = action;
  44751. action._actionManager = this._actionManager;
  44752. action._prepare();
  44753. return action;
  44754. };
  44755. Action.prototype._getProperty = function (propertyPath) {
  44756. return this._actionManager._getProperty(propertyPath);
  44757. };
  44758. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  44759. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44760. };
  44761. Action.prototype.serialize = function (parent) {
  44762. };
  44763. // Called by BABYLON.Action objects in serialize(...). Internal use
  44764. Action.prototype._serialize = function (serializedAction, parent) {
  44765. var serializationObject = {
  44766. type: 1,
  44767. children: [],
  44768. name: serializedAction.name,
  44769. properties: serializedAction.properties || []
  44770. };
  44771. // Serialize child
  44772. if (this._child) {
  44773. this._child.serialize(serializationObject);
  44774. }
  44775. // Check if "this" has a condition
  44776. if (this._condition) {
  44777. var serializedCondition = this._condition.serialize();
  44778. serializedCondition.children.push(serializationObject);
  44779. if (parent) {
  44780. parent.children.push(serializedCondition);
  44781. }
  44782. return serializedCondition;
  44783. }
  44784. if (parent) {
  44785. parent.children.push(serializationObject);
  44786. }
  44787. return serializationObject;
  44788. };
  44789. Action._SerializeValueAsString = function (value) {
  44790. if (typeof value === "number") {
  44791. return value.toString();
  44792. }
  44793. if (typeof value === "boolean") {
  44794. return value ? "true" : "false";
  44795. }
  44796. if (value instanceof BABYLON.Vector2) {
  44797. return value.x + ", " + value.y;
  44798. }
  44799. if (value instanceof BABYLON.Vector3) {
  44800. return value.x + ", " + value.y + ", " + value.z;
  44801. }
  44802. if (value instanceof BABYLON.Color3) {
  44803. return value.r + ", " + value.g + ", " + value.b;
  44804. }
  44805. if (value instanceof BABYLON.Color4) {
  44806. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  44807. }
  44808. return value; // string
  44809. };
  44810. Action._GetTargetProperty = function (target) {
  44811. return {
  44812. name: "target",
  44813. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  44814. : target instanceof BABYLON.Light ? "LightProperties"
  44815. : target instanceof BABYLON.Camera ? "CameraProperties"
  44816. : "SceneProperties",
  44817. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  44818. };
  44819. };
  44820. return Action;
  44821. }());
  44822. BABYLON.Action = Action;
  44823. })(BABYLON || (BABYLON = {}));
  44824. //# sourceMappingURL=babylon.action.js.map
  44825. var BABYLON;
  44826. (function (BABYLON) {
  44827. /**
  44828. * ActionEvent is the event beint sent when an action is triggered.
  44829. */
  44830. var ActionEvent = /** @class */ (function () {
  44831. /**
  44832. * @param source The mesh or sprite that triggered the action.
  44833. * @param pointerX The X mouse cursor position at the time of the event
  44834. * @param pointerY The Y mouse cursor position at the time of the event
  44835. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  44836. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  44837. */
  44838. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  44839. this.source = source;
  44840. this.pointerX = pointerX;
  44841. this.pointerY = pointerY;
  44842. this.meshUnderPointer = meshUnderPointer;
  44843. this.sourceEvent = sourceEvent;
  44844. this.additionalData = additionalData;
  44845. }
  44846. /**
  44847. * Helper function to auto-create an ActionEvent from a source mesh.
  44848. * @param source The source mesh that triggered the event
  44849. * @param evt {Event} The original (browser) event
  44850. */
  44851. ActionEvent.CreateNew = function (source, evt, additionalData) {
  44852. var scene = source.getScene();
  44853. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44854. };
  44855. /**
  44856. * Helper function to auto-create an ActionEvent from a source mesh.
  44857. * @param source The source sprite that triggered the event
  44858. * @param scene Scene associated with the sprite
  44859. * @param evt {Event} The original (browser) event
  44860. */
  44861. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  44862. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44863. };
  44864. /**
  44865. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  44866. * @param scene the scene where the event occurred
  44867. * @param evt {Event} The original (browser) event
  44868. */
  44869. ActionEvent.CreateNewFromScene = function (scene, evt) {
  44870. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  44871. };
  44872. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  44873. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  44874. };
  44875. return ActionEvent;
  44876. }());
  44877. BABYLON.ActionEvent = ActionEvent;
  44878. /**
  44879. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  44880. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  44881. */
  44882. var ActionManager = /** @class */ (function () {
  44883. function ActionManager(scene) {
  44884. // Members
  44885. this.actions = new Array();
  44886. this.hoverCursor = '';
  44887. this._scene = scene;
  44888. scene._actionManagers.push(this);
  44889. }
  44890. Object.defineProperty(ActionManager, "NothingTrigger", {
  44891. get: function () {
  44892. return ActionManager._NothingTrigger;
  44893. },
  44894. enumerable: true,
  44895. configurable: true
  44896. });
  44897. Object.defineProperty(ActionManager, "OnPickTrigger", {
  44898. get: function () {
  44899. return ActionManager._OnPickTrigger;
  44900. },
  44901. enumerable: true,
  44902. configurable: true
  44903. });
  44904. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  44905. get: function () {
  44906. return ActionManager._OnLeftPickTrigger;
  44907. },
  44908. enumerable: true,
  44909. configurable: true
  44910. });
  44911. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  44912. get: function () {
  44913. return ActionManager._OnRightPickTrigger;
  44914. },
  44915. enumerable: true,
  44916. configurable: true
  44917. });
  44918. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  44919. get: function () {
  44920. return ActionManager._OnCenterPickTrigger;
  44921. },
  44922. enumerable: true,
  44923. configurable: true
  44924. });
  44925. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  44926. get: function () {
  44927. return ActionManager._OnPickDownTrigger;
  44928. },
  44929. enumerable: true,
  44930. configurable: true
  44931. });
  44932. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  44933. get: function () {
  44934. return ActionManager._OnDoublePickTrigger;
  44935. },
  44936. enumerable: true,
  44937. configurable: true
  44938. });
  44939. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  44940. get: function () {
  44941. return ActionManager._OnPickUpTrigger;
  44942. },
  44943. enumerable: true,
  44944. configurable: true
  44945. });
  44946. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  44947. /// This trigger will only be raised if you also declared a OnPickDown
  44948. get: function () {
  44949. return ActionManager._OnPickOutTrigger;
  44950. },
  44951. enumerable: true,
  44952. configurable: true
  44953. });
  44954. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  44955. get: function () {
  44956. return ActionManager._OnLongPressTrigger;
  44957. },
  44958. enumerable: true,
  44959. configurable: true
  44960. });
  44961. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  44962. get: function () {
  44963. return ActionManager._OnPointerOverTrigger;
  44964. },
  44965. enumerable: true,
  44966. configurable: true
  44967. });
  44968. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  44969. get: function () {
  44970. return ActionManager._OnPointerOutTrigger;
  44971. },
  44972. enumerable: true,
  44973. configurable: true
  44974. });
  44975. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  44976. get: function () {
  44977. return ActionManager._OnEveryFrameTrigger;
  44978. },
  44979. enumerable: true,
  44980. configurable: true
  44981. });
  44982. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  44983. get: function () {
  44984. return ActionManager._OnIntersectionEnterTrigger;
  44985. },
  44986. enumerable: true,
  44987. configurable: true
  44988. });
  44989. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  44990. get: function () {
  44991. return ActionManager._OnIntersectionExitTrigger;
  44992. },
  44993. enumerable: true,
  44994. configurable: true
  44995. });
  44996. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  44997. get: function () {
  44998. return ActionManager._OnKeyDownTrigger;
  44999. },
  45000. enumerable: true,
  45001. configurable: true
  45002. });
  45003. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45004. get: function () {
  45005. return ActionManager._OnKeyUpTrigger;
  45006. },
  45007. enumerable: true,
  45008. configurable: true
  45009. });
  45010. // Methods
  45011. ActionManager.prototype.dispose = function () {
  45012. var index = this._scene._actionManagers.indexOf(this);
  45013. for (var i = 0; i < this.actions.length; i++) {
  45014. var action = this.actions[i];
  45015. ActionManager.Triggers[action.trigger]--;
  45016. if (ActionManager.Triggers[action.trigger] === 0) {
  45017. delete ActionManager.Triggers[action.trigger];
  45018. }
  45019. }
  45020. if (index > -1) {
  45021. this._scene._actionManagers.splice(index, 1);
  45022. }
  45023. };
  45024. ActionManager.prototype.getScene = function () {
  45025. return this._scene;
  45026. };
  45027. /**
  45028. * Does this action manager handles actions of any of the given triggers
  45029. * @param {number[]} triggers - the triggers to be tested
  45030. * @return {boolean} whether one (or more) of the triggers is handeled
  45031. */
  45032. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45033. for (var index = 0; index < this.actions.length; index++) {
  45034. var action = this.actions[index];
  45035. if (triggers.indexOf(action.trigger) > -1) {
  45036. return true;
  45037. }
  45038. }
  45039. return false;
  45040. };
  45041. /**
  45042. * Does this action manager handles actions of a given trigger
  45043. * @param {number} trigger - the trigger to be tested
  45044. * @return {boolean} whether the trigger is handeled
  45045. */
  45046. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45047. for (var index = 0; index < this.actions.length; index++) {
  45048. var action = this.actions[index];
  45049. if (action.trigger === trigger) {
  45050. return true;
  45051. }
  45052. }
  45053. return false;
  45054. };
  45055. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45056. /**
  45057. * Does this action manager has pointer triggers
  45058. * @return {boolean} whether or not it has pointer triggers
  45059. */
  45060. get: function () {
  45061. for (var index = 0; index < this.actions.length; index++) {
  45062. var action = this.actions[index];
  45063. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45064. return true;
  45065. }
  45066. }
  45067. return false;
  45068. },
  45069. enumerable: true,
  45070. configurable: true
  45071. });
  45072. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45073. /**
  45074. * Does this action manager has pick triggers
  45075. * @return {boolean} whether or not it has pick triggers
  45076. */
  45077. get: function () {
  45078. for (var index = 0; index < this.actions.length; index++) {
  45079. var action = this.actions[index];
  45080. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45081. return true;
  45082. }
  45083. }
  45084. return false;
  45085. },
  45086. enumerable: true,
  45087. configurable: true
  45088. });
  45089. Object.defineProperty(ActionManager, "HasTriggers", {
  45090. /**
  45091. * Does exist one action manager with at least one trigger
  45092. * @return {boolean} whether or not it exists one action manager with one trigger
  45093. **/
  45094. get: function () {
  45095. for (var t in ActionManager.Triggers) {
  45096. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45097. return true;
  45098. }
  45099. }
  45100. return false;
  45101. },
  45102. enumerable: true,
  45103. configurable: true
  45104. });
  45105. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45106. /**
  45107. * Does exist one action manager with at least one pick trigger
  45108. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45109. **/
  45110. get: function () {
  45111. for (var t in ActionManager.Triggers) {
  45112. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45113. var t_int = parseInt(t);
  45114. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45115. return true;
  45116. }
  45117. }
  45118. }
  45119. return false;
  45120. },
  45121. enumerable: true,
  45122. configurable: true
  45123. });
  45124. /**
  45125. * Does exist one action manager that handles actions of a given trigger
  45126. * @param {number} trigger - the trigger to be tested
  45127. * @return {boolean} whether the trigger is handeled by at least one action manager
  45128. **/
  45129. ActionManager.HasSpecificTrigger = function (trigger) {
  45130. for (var t in ActionManager.Triggers) {
  45131. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45132. var t_int = parseInt(t);
  45133. if (t_int === trigger) {
  45134. return true;
  45135. }
  45136. }
  45137. }
  45138. return false;
  45139. };
  45140. /**
  45141. * Registers an action to this action manager
  45142. * @param {BABYLON.Action} action - the action to be registered
  45143. * @return {BABYLON.Action} the action amended (prepared) after registration
  45144. */
  45145. ActionManager.prototype.registerAction = function (action) {
  45146. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  45147. if (this.getScene().actionManager !== this) {
  45148. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  45149. return null;
  45150. }
  45151. }
  45152. this.actions.push(action);
  45153. if (ActionManager.Triggers[action.trigger]) {
  45154. ActionManager.Triggers[action.trigger]++;
  45155. }
  45156. else {
  45157. ActionManager.Triggers[action.trigger] = 1;
  45158. }
  45159. action._actionManager = this;
  45160. action._prepare();
  45161. return action;
  45162. };
  45163. /**
  45164. * Unregisters an action to this action manager
  45165. * @param action The action to be unregistered
  45166. * @return whether the action has been unregistered
  45167. */
  45168. ActionManager.prototype.unregisterAction = function (action) {
  45169. var index = this.actions.indexOf(action);
  45170. if (index !== -1) {
  45171. this.actions.splice(index, 1);
  45172. ActionManager.Triggers[action.trigger] -= 1;
  45173. if (ActionManager.Triggers[action.trigger] === 0) {
  45174. delete ActionManager.Triggers[action.trigger];
  45175. }
  45176. delete action._actionManager;
  45177. return true;
  45178. }
  45179. return false;
  45180. };
  45181. /**
  45182. * Process a specific trigger
  45183. * @param {number} trigger - the trigger to process
  45184. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45185. */
  45186. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45187. for (var index = 0; index < this.actions.length; index++) {
  45188. var action = this.actions[index];
  45189. if (action.trigger === trigger) {
  45190. if (evt) {
  45191. if (trigger === ActionManager.OnKeyUpTrigger
  45192. || trigger === ActionManager.OnKeyDownTrigger) {
  45193. var parameter = action.getTriggerParameter();
  45194. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45195. if (!parameter.toLowerCase) {
  45196. continue;
  45197. }
  45198. var lowerCase = parameter.toLowerCase();
  45199. if (lowerCase !== evt.sourceEvent.key) {
  45200. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45201. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45202. if (actualkey !== lowerCase) {
  45203. continue;
  45204. }
  45205. }
  45206. }
  45207. }
  45208. }
  45209. action._executeCurrent(evt);
  45210. }
  45211. }
  45212. };
  45213. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45214. var properties = propertyPath.split(".");
  45215. for (var index = 0; index < properties.length - 1; index++) {
  45216. target = target[properties[index]];
  45217. }
  45218. return target;
  45219. };
  45220. ActionManager.prototype._getProperty = function (propertyPath) {
  45221. var properties = propertyPath.split(".");
  45222. return properties[properties.length - 1];
  45223. };
  45224. ActionManager.prototype.serialize = function (name) {
  45225. var root = {
  45226. children: new Array(),
  45227. name: name,
  45228. type: 3,
  45229. properties: new Array() // Empty for root but required
  45230. };
  45231. for (var i = 0; i < this.actions.length; i++) {
  45232. var triggerObject = {
  45233. type: 0,
  45234. children: new Array(),
  45235. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45236. properties: new Array()
  45237. };
  45238. var triggerOptions = this.actions[i].triggerOptions;
  45239. if (triggerOptions && typeof triggerOptions !== "number") {
  45240. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45241. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45242. }
  45243. else {
  45244. var parameter = {};
  45245. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45246. if (triggerOptions.parameter.mesh) {
  45247. parameter._meshId = triggerOptions.parameter.mesh.id;
  45248. }
  45249. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45250. }
  45251. }
  45252. // Serialize child action, recursively
  45253. this.actions[i].serialize(triggerObject);
  45254. // Add serialized trigger
  45255. root.children.push(triggerObject);
  45256. }
  45257. return root;
  45258. };
  45259. ActionManager.Parse = function (parsedActions, object, scene) {
  45260. var actionManager = new ActionManager(scene);
  45261. if (object === null)
  45262. scene.actionManager = actionManager;
  45263. else
  45264. object.actionManager = actionManager;
  45265. // instanciate a new object
  45266. var instanciate = function (name, params) {
  45267. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  45268. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  45269. newInstance.constructor.apply(newInstance, params);
  45270. return newInstance;
  45271. };
  45272. var parseParameter = function (name, value, target, propertyPath) {
  45273. if (propertyPath === null) {
  45274. // String, boolean or float
  45275. var floatValue = parseFloat(value);
  45276. if (value === "true" || value === "false")
  45277. return value === "true";
  45278. else
  45279. return isNaN(floatValue) ? value : floatValue;
  45280. }
  45281. var effectiveTarget = propertyPath.split(".");
  45282. var values = value.split(",");
  45283. // Get effective Target
  45284. for (var i = 0; i < effectiveTarget.length; i++) {
  45285. target = target[effectiveTarget[i]];
  45286. }
  45287. // Return appropriate value with its type
  45288. if (typeof (target) === "boolean")
  45289. return values[0] === "true";
  45290. if (typeof (target) === "string")
  45291. return values[0];
  45292. // Parameters with multiple values such as Vector3 etc.
  45293. var split = new Array();
  45294. for (var i = 0; i < values.length; i++)
  45295. split.push(parseFloat(values[i]));
  45296. if (target instanceof BABYLON.Vector3)
  45297. return BABYLON.Vector3.FromArray(split);
  45298. if (target instanceof BABYLON.Vector4)
  45299. return BABYLON.Vector4.FromArray(split);
  45300. if (target instanceof BABYLON.Color3)
  45301. return BABYLON.Color3.FromArray(split);
  45302. if (target instanceof BABYLON.Color4)
  45303. return BABYLON.Color4.FromArray(split);
  45304. return parseFloat(values[0]);
  45305. };
  45306. // traverse graph per trigger
  45307. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45308. if (combineArray === void 0) { combineArray = null; }
  45309. if (parsedAction.detached)
  45310. return;
  45311. var parameters = new Array();
  45312. var target = null;
  45313. var propertyPath = null;
  45314. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45315. // Parameters
  45316. if (parsedAction.type === 2)
  45317. parameters.push(actionManager);
  45318. else
  45319. parameters.push(trigger);
  45320. if (combine) {
  45321. var actions = new Array();
  45322. for (var j = 0; j < parsedAction.combine.length; j++) {
  45323. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  45324. }
  45325. parameters.push(actions);
  45326. }
  45327. else {
  45328. for (var i = 0; i < parsedAction.properties.length; i++) {
  45329. var value = parsedAction.properties[i].value;
  45330. var name = parsedAction.properties[i].name;
  45331. var targetType = parsedAction.properties[i].targetType;
  45332. if (name === "target")
  45333. if (targetType !== null && targetType === "SceneProperties")
  45334. value = target = scene;
  45335. else
  45336. value = target = scene.getNodeByName(value);
  45337. else if (name === "parent")
  45338. value = scene.getNodeByName(value);
  45339. else if (name === "sound")
  45340. value = scene.getSoundByName(value);
  45341. else if (name !== "propertyPath") {
  45342. if (parsedAction.type === 2 && name === "operator")
  45343. value = BABYLON.ValueCondition[value];
  45344. else
  45345. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  45346. }
  45347. else {
  45348. propertyPath = value;
  45349. }
  45350. parameters.push(value);
  45351. }
  45352. }
  45353. if (combineArray === null) {
  45354. parameters.push(condition);
  45355. }
  45356. else {
  45357. parameters.push(null);
  45358. }
  45359. // If interpolate value action
  45360. if (parsedAction.name === "InterpolateValueAction") {
  45361. var param = parameters[parameters.length - 2];
  45362. parameters[parameters.length - 1] = param;
  45363. parameters[parameters.length - 2] = condition;
  45364. }
  45365. // Action or condition(s) and not CombineAction
  45366. var newAction = instanciate(parsedAction.name, parameters);
  45367. if (newAction instanceof BABYLON.Condition && condition !== null) {
  45368. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  45369. if (action)
  45370. action.then(nothing);
  45371. else
  45372. actionManager.registerAction(nothing);
  45373. action = nothing;
  45374. }
  45375. if (combineArray === null) {
  45376. if (newAction instanceof BABYLON.Condition) {
  45377. condition = newAction;
  45378. newAction = action;
  45379. }
  45380. else {
  45381. condition = null;
  45382. if (action)
  45383. action.then(newAction);
  45384. else
  45385. actionManager.registerAction(newAction);
  45386. }
  45387. }
  45388. else {
  45389. combineArray.push(newAction);
  45390. }
  45391. for (var i = 0; i < parsedAction.children.length; i++)
  45392. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45393. };
  45394. // triggers
  45395. for (var i = 0; i < parsedActions.children.length; i++) {
  45396. var triggerParams;
  45397. var trigger = parsedActions.children[i];
  45398. if (trigger.properties.length > 0) {
  45399. var param = trigger.properties[0].value;
  45400. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45401. if (value._meshId) {
  45402. value.mesh = scene.getMeshByID(value._meshId);
  45403. }
  45404. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45405. }
  45406. else
  45407. triggerParams = ActionManager[trigger.name];
  45408. for (var j = 0; j < trigger.children.length; j++) {
  45409. if (!trigger.detached)
  45410. traverse(trigger.children[j], triggerParams, null, null);
  45411. }
  45412. }
  45413. };
  45414. ActionManager.GetTriggerName = function (trigger) {
  45415. switch (trigger) {
  45416. case 0: return "NothingTrigger";
  45417. case 1: return "OnPickTrigger";
  45418. case 2: return "OnLeftPickTrigger";
  45419. case 3: return "OnRightPickTrigger";
  45420. case 4: return "OnCenterPickTrigger";
  45421. case 5: return "OnPickDownTrigger";
  45422. case 6: return "OnPickUpTrigger";
  45423. case 7: return "OnLongPressTrigger";
  45424. case 8: return "OnPointerOverTrigger";
  45425. case 9: return "OnPointerOutTrigger";
  45426. case 10: return "OnEveryFrameTrigger";
  45427. case 11: return "OnIntersectionEnterTrigger";
  45428. case 12: return "OnIntersectionExitTrigger";
  45429. case 13: return "OnKeyDownTrigger";
  45430. case 14: return "OnKeyUpTrigger";
  45431. case 15: return "OnPickOutTrigger";
  45432. default: return "";
  45433. }
  45434. };
  45435. // Statics
  45436. ActionManager._NothingTrigger = 0;
  45437. ActionManager._OnPickTrigger = 1;
  45438. ActionManager._OnLeftPickTrigger = 2;
  45439. ActionManager._OnRightPickTrigger = 3;
  45440. ActionManager._OnCenterPickTrigger = 4;
  45441. ActionManager._OnPickDownTrigger = 5;
  45442. ActionManager._OnDoublePickTrigger = 6;
  45443. ActionManager._OnPickUpTrigger = 7;
  45444. ActionManager._OnLongPressTrigger = 8;
  45445. ActionManager._OnPointerOverTrigger = 9;
  45446. ActionManager._OnPointerOutTrigger = 10;
  45447. ActionManager._OnEveryFrameTrigger = 11;
  45448. ActionManager._OnIntersectionEnterTrigger = 12;
  45449. ActionManager._OnIntersectionExitTrigger = 13;
  45450. ActionManager._OnKeyDownTrigger = 14;
  45451. ActionManager._OnKeyUpTrigger = 15;
  45452. ActionManager._OnPickOutTrigger = 16;
  45453. ActionManager.Triggers = {};
  45454. return ActionManager;
  45455. }());
  45456. BABYLON.ActionManager = ActionManager;
  45457. })(BABYLON || (BABYLON = {}));
  45458. //# sourceMappingURL=babylon.actionManager.js.map
  45459. var BABYLON;
  45460. (function (BABYLON) {
  45461. var InterpolateValueAction = /** @class */ (function (_super) {
  45462. __extends(InterpolateValueAction, _super);
  45463. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45464. if (duration === void 0) { duration = 1000; }
  45465. var _this = _super.call(this, triggerOptions, condition) || this;
  45466. _this.propertyPath = propertyPath;
  45467. _this.value = value;
  45468. _this.duration = duration;
  45469. _this.stopOtherAnimations = stopOtherAnimations;
  45470. _this.onInterpolationDone = onInterpolationDone;
  45471. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45472. _this._target = _this._effectiveTarget = target;
  45473. return _this;
  45474. }
  45475. InterpolateValueAction.prototype._prepare = function () {
  45476. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45477. this._property = this._getProperty(this.propertyPath);
  45478. };
  45479. InterpolateValueAction.prototype.execute = function () {
  45480. var _this = this;
  45481. var scene = this._actionManager.getScene();
  45482. var keys = [
  45483. {
  45484. frame: 0,
  45485. value: this._effectiveTarget[this._property]
  45486. }, {
  45487. frame: 100,
  45488. value: this.value
  45489. }
  45490. ];
  45491. var dataType;
  45492. if (typeof this.value === "number") {
  45493. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45494. }
  45495. else if (this.value instanceof BABYLON.Color3) {
  45496. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45497. }
  45498. else if (this.value instanceof BABYLON.Vector3) {
  45499. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45500. }
  45501. else if (this.value instanceof BABYLON.Matrix) {
  45502. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45503. }
  45504. else if (this.value instanceof BABYLON.Quaternion) {
  45505. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45506. }
  45507. else {
  45508. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45509. return;
  45510. }
  45511. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45512. animation.setKeys(keys);
  45513. if (this.stopOtherAnimations) {
  45514. scene.stopAnimation(this._effectiveTarget);
  45515. }
  45516. var wrapper = function () {
  45517. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45518. if (_this.onInterpolationDone) {
  45519. _this.onInterpolationDone();
  45520. }
  45521. };
  45522. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45523. };
  45524. InterpolateValueAction.prototype.serialize = function (parent) {
  45525. return _super.prototype._serialize.call(this, {
  45526. name: "InterpolateValueAction",
  45527. properties: [
  45528. BABYLON.Action._GetTargetProperty(this._target),
  45529. { name: "propertyPath", value: this.propertyPath },
  45530. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45531. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45532. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45533. ]
  45534. }, parent);
  45535. };
  45536. return InterpolateValueAction;
  45537. }(BABYLON.Action));
  45538. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45539. })(BABYLON || (BABYLON = {}));
  45540. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45541. var BABYLON;
  45542. (function (BABYLON) {
  45543. var SwitchBooleanAction = /** @class */ (function (_super) {
  45544. __extends(SwitchBooleanAction, _super);
  45545. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45546. var _this = _super.call(this, triggerOptions, condition) || this;
  45547. _this.propertyPath = propertyPath;
  45548. _this._target = _this._effectiveTarget = target;
  45549. return _this;
  45550. }
  45551. SwitchBooleanAction.prototype._prepare = function () {
  45552. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45553. this._property = this._getProperty(this.propertyPath);
  45554. };
  45555. SwitchBooleanAction.prototype.execute = function () {
  45556. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45557. };
  45558. SwitchBooleanAction.prototype.serialize = function (parent) {
  45559. return _super.prototype._serialize.call(this, {
  45560. name: "SwitchBooleanAction",
  45561. properties: [
  45562. BABYLON.Action._GetTargetProperty(this._target),
  45563. { name: "propertyPath", value: this.propertyPath }
  45564. ]
  45565. }, parent);
  45566. };
  45567. return SwitchBooleanAction;
  45568. }(BABYLON.Action));
  45569. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45570. var SetStateAction = /** @class */ (function (_super) {
  45571. __extends(SetStateAction, _super);
  45572. function SetStateAction(triggerOptions, target, value, condition) {
  45573. var _this = _super.call(this, triggerOptions, condition) || this;
  45574. _this.value = value;
  45575. _this._target = target;
  45576. return _this;
  45577. }
  45578. SetStateAction.prototype.execute = function () {
  45579. this._target.state = this.value;
  45580. };
  45581. SetStateAction.prototype.serialize = function (parent) {
  45582. return _super.prototype._serialize.call(this, {
  45583. name: "SetStateAction",
  45584. properties: [
  45585. BABYLON.Action._GetTargetProperty(this._target),
  45586. { name: "value", value: this.value }
  45587. ]
  45588. }, parent);
  45589. };
  45590. return SetStateAction;
  45591. }(BABYLON.Action));
  45592. BABYLON.SetStateAction = SetStateAction;
  45593. var SetValueAction = /** @class */ (function (_super) {
  45594. __extends(SetValueAction, _super);
  45595. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45596. var _this = _super.call(this, triggerOptions, condition) || this;
  45597. _this.propertyPath = propertyPath;
  45598. _this.value = value;
  45599. _this._target = _this._effectiveTarget = target;
  45600. return _this;
  45601. }
  45602. SetValueAction.prototype._prepare = function () {
  45603. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45604. this._property = this._getProperty(this.propertyPath);
  45605. };
  45606. SetValueAction.prototype.execute = function () {
  45607. this._effectiveTarget[this._property] = this.value;
  45608. if (this._target.markAsDirty) {
  45609. this._target.markAsDirty(this._property);
  45610. }
  45611. };
  45612. SetValueAction.prototype.serialize = function (parent) {
  45613. return _super.prototype._serialize.call(this, {
  45614. name: "SetValueAction",
  45615. properties: [
  45616. BABYLON.Action._GetTargetProperty(this._target),
  45617. { name: "propertyPath", value: this.propertyPath },
  45618. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45619. ]
  45620. }, parent);
  45621. };
  45622. return SetValueAction;
  45623. }(BABYLON.Action));
  45624. BABYLON.SetValueAction = SetValueAction;
  45625. var IncrementValueAction = /** @class */ (function (_super) {
  45626. __extends(IncrementValueAction, _super);
  45627. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45628. var _this = _super.call(this, triggerOptions, condition) || this;
  45629. _this.propertyPath = propertyPath;
  45630. _this.value = value;
  45631. _this._target = _this._effectiveTarget = target;
  45632. return _this;
  45633. }
  45634. IncrementValueAction.prototype._prepare = function () {
  45635. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45636. this._property = this._getProperty(this.propertyPath);
  45637. if (typeof this._effectiveTarget[this._property] !== "number") {
  45638. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45639. }
  45640. };
  45641. IncrementValueAction.prototype.execute = function () {
  45642. this._effectiveTarget[this._property] += this.value;
  45643. if (this._target.markAsDirty) {
  45644. this._target.markAsDirty(this._property);
  45645. }
  45646. };
  45647. IncrementValueAction.prototype.serialize = function (parent) {
  45648. return _super.prototype._serialize.call(this, {
  45649. name: "IncrementValueAction",
  45650. properties: [
  45651. BABYLON.Action._GetTargetProperty(this._target),
  45652. { name: "propertyPath", value: this.propertyPath },
  45653. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45654. ]
  45655. }, parent);
  45656. };
  45657. return IncrementValueAction;
  45658. }(BABYLON.Action));
  45659. BABYLON.IncrementValueAction = IncrementValueAction;
  45660. var PlayAnimationAction = /** @class */ (function (_super) {
  45661. __extends(PlayAnimationAction, _super);
  45662. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  45663. var _this = _super.call(this, triggerOptions, condition) || this;
  45664. _this.from = from;
  45665. _this.to = to;
  45666. _this.loop = loop;
  45667. _this._target = target;
  45668. return _this;
  45669. }
  45670. PlayAnimationAction.prototype._prepare = function () {
  45671. };
  45672. PlayAnimationAction.prototype.execute = function () {
  45673. var scene = this._actionManager.getScene();
  45674. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  45675. };
  45676. PlayAnimationAction.prototype.serialize = function (parent) {
  45677. return _super.prototype._serialize.call(this, {
  45678. name: "PlayAnimationAction",
  45679. properties: [
  45680. BABYLON.Action._GetTargetProperty(this._target),
  45681. { name: "from", value: String(this.from) },
  45682. { name: "to", value: String(this.to) },
  45683. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  45684. ]
  45685. }, parent);
  45686. };
  45687. return PlayAnimationAction;
  45688. }(BABYLON.Action));
  45689. BABYLON.PlayAnimationAction = PlayAnimationAction;
  45690. var StopAnimationAction = /** @class */ (function (_super) {
  45691. __extends(StopAnimationAction, _super);
  45692. function StopAnimationAction(triggerOptions, target, condition) {
  45693. var _this = _super.call(this, triggerOptions, condition) || this;
  45694. _this._target = target;
  45695. return _this;
  45696. }
  45697. StopAnimationAction.prototype._prepare = function () {
  45698. };
  45699. StopAnimationAction.prototype.execute = function () {
  45700. var scene = this._actionManager.getScene();
  45701. scene.stopAnimation(this._target);
  45702. };
  45703. StopAnimationAction.prototype.serialize = function (parent) {
  45704. return _super.prototype._serialize.call(this, {
  45705. name: "StopAnimationAction",
  45706. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  45707. }, parent);
  45708. };
  45709. return StopAnimationAction;
  45710. }(BABYLON.Action));
  45711. BABYLON.StopAnimationAction = StopAnimationAction;
  45712. var DoNothingAction = /** @class */ (function (_super) {
  45713. __extends(DoNothingAction, _super);
  45714. function DoNothingAction(triggerOptions, condition) {
  45715. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  45716. return _super.call(this, triggerOptions, condition) || this;
  45717. }
  45718. DoNothingAction.prototype.execute = function () {
  45719. };
  45720. DoNothingAction.prototype.serialize = function (parent) {
  45721. return _super.prototype._serialize.call(this, {
  45722. name: "DoNothingAction",
  45723. properties: []
  45724. }, parent);
  45725. };
  45726. return DoNothingAction;
  45727. }(BABYLON.Action));
  45728. BABYLON.DoNothingAction = DoNothingAction;
  45729. var CombineAction = /** @class */ (function (_super) {
  45730. __extends(CombineAction, _super);
  45731. function CombineAction(triggerOptions, children, condition) {
  45732. var _this = _super.call(this, triggerOptions, condition) || this;
  45733. _this.children = children;
  45734. return _this;
  45735. }
  45736. CombineAction.prototype._prepare = function () {
  45737. for (var index = 0; index < this.children.length; index++) {
  45738. this.children[index]._actionManager = this._actionManager;
  45739. this.children[index]._prepare();
  45740. }
  45741. };
  45742. CombineAction.prototype.execute = function (evt) {
  45743. for (var index = 0; index < this.children.length; index++) {
  45744. this.children[index].execute(evt);
  45745. }
  45746. };
  45747. CombineAction.prototype.serialize = function (parent) {
  45748. var serializationObject = _super.prototype._serialize.call(this, {
  45749. name: "CombineAction",
  45750. properties: [],
  45751. combine: []
  45752. }, parent);
  45753. for (var i = 0; i < this.children.length; i++) {
  45754. serializationObject.combine.push(this.children[i].serialize(null));
  45755. }
  45756. return serializationObject;
  45757. };
  45758. return CombineAction;
  45759. }(BABYLON.Action));
  45760. BABYLON.CombineAction = CombineAction;
  45761. var ExecuteCodeAction = /** @class */ (function (_super) {
  45762. __extends(ExecuteCodeAction, _super);
  45763. function ExecuteCodeAction(triggerOptions, func, condition) {
  45764. var _this = _super.call(this, triggerOptions, condition) || this;
  45765. _this.func = func;
  45766. return _this;
  45767. }
  45768. ExecuteCodeAction.prototype.execute = function (evt) {
  45769. this.func(evt);
  45770. };
  45771. return ExecuteCodeAction;
  45772. }(BABYLON.Action));
  45773. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  45774. var SetParentAction = /** @class */ (function (_super) {
  45775. __extends(SetParentAction, _super);
  45776. function SetParentAction(triggerOptions, target, parent, condition) {
  45777. var _this = _super.call(this, triggerOptions, condition) || this;
  45778. _this._target = target;
  45779. _this._parent = parent;
  45780. return _this;
  45781. }
  45782. SetParentAction.prototype._prepare = function () {
  45783. };
  45784. SetParentAction.prototype.execute = function () {
  45785. if (this._target.parent === this._parent) {
  45786. return;
  45787. }
  45788. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  45789. invertParentWorldMatrix.invert();
  45790. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  45791. this._target.parent = this._parent;
  45792. };
  45793. SetParentAction.prototype.serialize = function (parent) {
  45794. return _super.prototype._serialize.call(this, {
  45795. name: "SetParentAction",
  45796. properties: [
  45797. BABYLON.Action._GetTargetProperty(this._target),
  45798. BABYLON.Action._GetTargetProperty(this._parent),
  45799. ]
  45800. }, parent);
  45801. };
  45802. return SetParentAction;
  45803. }(BABYLON.Action));
  45804. BABYLON.SetParentAction = SetParentAction;
  45805. var PlaySoundAction = /** @class */ (function (_super) {
  45806. __extends(PlaySoundAction, _super);
  45807. function PlaySoundAction(triggerOptions, sound, condition) {
  45808. var _this = _super.call(this, triggerOptions, condition) || this;
  45809. _this._sound = sound;
  45810. return _this;
  45811. }
  45812. PlaySoundAction.prototype._prepare = function () {
  45813. };
  45814. PlaySoundAction.prototype.execute = function () {
  45815. if (this._sound !== undefined)
  45816. this._sound.play();
  45817. };
  45818. PlaySoundAction.prototype.serialize = function (parent) {
  45819. return _super.prototype._serialize.call(this, {
  45820. name: "PlaySoundAction",
  45821. properties: [{ name: "sound", value: this._sound.name }]
  45822. }, parent);
  45823. };
  45824. return PlaySoundAction;
  45825. }(BABYLON.Action));
  45826. BABYLON.PlaySoundAction = PlaySoundAction;
  45827. var StopSoundAction = /** @class */ (function (_super) {
  45828. __extends(StopSoundAction, _super);
  45829. function StopSoundAction(triggerOptions, sound, condition) {
  45830. var _this = _super.call(this, triggerOptions, condition) || this;
  45831. _this._sound = sound;
  45832. return _this;
  45833. }
  45834. StopSoundAction.prototype._prepare = function () {
  45835. };
  45836. StopSoundAction.prototype.execute = function () {
  45837. if (this._sound !== undefined)
  45838. this._sound.stop();
  45839. };
  45840. StopSoundAction.prototype.serialize = function (parent) {
  45841. return _super.prototype._serialize.call(this, {
  45842. name: "StopSoundAction",
  45843. properties: [{ name: "sound", value: this._sound.name }]
  45844. }, parent);
  45845. };
  45846. return StopSoundAction;
  45847. }(BABYLON.Action));
  45848. BABYLON.StopSoundAction = StopSoundAction;
  45849. })(BABYLON || (BABYLON = {}));
  45850. //# sourceMappingURL=babylon.directActions.js.map
  45851. var BABYLON;
  45852. (function (BABYLON) {
  45853. var SpriteManager = /** @class */ (function () {
  45854. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  45855. if (epsilon === void 0) { epsilon = 0.01; }
  45856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45857. this.name = name;
  45858. this.sprites = new Array();
  45859. this.renderingGroupId = 0;
  45860. this.layerMask = 0x0FFFFFFF;
  45861. this.fogEnabled = true;
  45862. this.isPickable = false;
  45863. /**
  45864. * An event triggered when the manager is disposed.
  45865. * @type {BABYLON.Observable}
  45866. */
  45867. this.onDisposeObservable = new BABYLON.Observable();
  45868. this._vertexBuffers = {};
  45869. this._capacity = capacity;
  45870. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  45871. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45872. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45873. if (cellSize.width && cellSize.height) {
  45874. this.cellWidth = cellSize.width;
  45875. this.cellHeight = cellSize.height;
  45876. }
  45877. else if (cellSize !== undefined) {
  45878. this.cellWidth = cellSize;
  45879. this.cellHeight = cellSize;
  45880. }
  45881. else {
  45882. return;
  45883. }
  45884. this._epsilon = epsilon;
  45885. this._scene = scene;
  45886. this._scene.spriteManagers.push(this);
  45887. var indices = [];
  45888. var index = 0;
  45889. for (var count = 0; count < capacity; count++) {
  45890. indices.push(index);
  45891. indices.push(index + 1);
  45892. indices.push(index + 2);
  45893. indices.push(index);
  45894. indices.push(index + 2);
  45895. indices.push(index + 3);
  45896. index += 4;
  45897. }
  45898. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  45899. // VBO
  45900. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  45901. this._vertexData = new Float32Array(capacity * 16 * 4);
  45902. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  45903. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  45904. var options = this._buffer.createVertexBuffer("options", 4, 4);
  45905. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  45906. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  45907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45908. this._vertexBuffers["options"] = options;
  45909. this._vertexBuffers["cellInfo"] = cellInfo;
  45910. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45911. // Effects
  45912. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  45913. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  45914. }
  45915. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  45916. set: function (callback) {
  45917. if (this._onDisposeObserver) {
  45918. this.onDisposeObservable.remove(this._onDisposeObserver);
  45919. }
  45920. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45921. },
  45922. enumerable: true,
  45923. configurable: true
  45924. });
  45925. Object.defineProperty(SpriteManager.prototype, "texture", {
  45926. get: function () {
  45927. return this._spriteTexture;
  45928. },
  45929. set: function (value) {
  45930. this._spriteTexture = value;
  45931. },
  45932. enumerable: true,
  45933. configurable: true
  45934. });
  45935. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  45936. var arrayOffset = index * 16;
  45937. if (offsetX === 0)
  45938. offsetX = this._epsilon;
  45939. else if (offsetX === 1)
  45940. offsetX = 1 - this._epsilon;
  45941. if (offsetY === 0)
  45942. offsetY = this._epsilon;
  45943. else if (offsetY === 1)
  45944. offsetY = 1 - this._epsilon;
  45945. this._vertexData[arrayOffset] = sprite.position.x;
  45946. this._vertexData[arrayOffset + 1] = sprite.position.y;
  45947. this._vertexData[arrayOffset + 2] = sprite.position.z;
  45948. this._vertexData[arrayOffset + 3] = sprite.angle;
  45949. this._vertexData[arrayOffset + 4] = sprite.width;
  45950. this._vertexData[arrayOffset + 5] = sprite.height;
  45951. this._vertexData[arrayOffset + 6] = offsetX;
  45952. this._vertexData[arrayOffset + 7] = offsetY;
  45953. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  45954. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  45955. var offset = (sprite.cellIndex / rowSize) >> 0;
  45956. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  45957. this._vertexData[arrayOffset + 11] = offset;
  45958. // Color
  45959. this._vertexData[arrayOffset + 12] = sprite.color.r;
  45960. this._vertexData[arrayOffset + 13] = sprite.color.g;
  45961. this._vertexData[arrayOffset + 14] = sprite.color.b;
  45962. this._vertexData[arrayOffset + 15] = sprite.color.a;
  45963. };
  45964. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  45965. var count = Math.min(this._capacity, this.sprites.length);
  45966. var min = BABYLON.Vector3.Zero();
  45967. var max = BABYLON.Vector3.Zero();
  45968. var distance = Number.MAX_VALUE;
  45969. var currentSprite = null;
  45970. var cameraSpacePosition = BABYLON.Vector3.Zero();
  45971. var cameraView = camera.getViewMatrix();
  45972. for (var index = 0; index < count; index++) {
  45973. var sprite = this.sprites[index];
  45974. if (!sprite) {
  45975. continue;
  45976. }
  45977. if (predicate) {
  45978. if (!predicate(sprite)) {
  45979. continue;
  45980. }
  45981. }
  45982. else if (!sprite.isPickable) {
  45983. continue;
  45984. }
  45985. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  45986. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  45987. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  45988. if (ray.intersectsBoxMinMax(min, max)) {
  45989. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  45990. if (distance > currentDistance) {
  45991. distance = currentDistance;
  45992. currentSprite = sprite;
  45993. if (fastCheck) {
  45994. break;
  45995. }
  45996. }
  45997. }
  45998. }
  45999. if (currentSprite) {
  46000. var result = new BABYLON.PickingInfo();
  46001. result.hit = true;
  46002. result.pickedSprite = currentSprite;
  46003. result.distance = distance;
  46004. return result;
  46005. }
  46006. return null;
  46007. };
  46008. SpriteManager.prototype.render = function () {
  46009. // Check
  46010. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46011. return;
  46012. var engine = this._scene.getEngine();
  46013. var baseSize = this._spriteTexture.getBaseSize();
  46014. // Sprites
  46015. var deltaTime = engine.getDeltaTime();
  46016. var max = Math.min(this._capacity, this.sprites.length);
  46017. var rowSize = baseSize.width / this.cellWidth;
  46018. var offset = 0;
  46019. for (var index = 0; index < max; index++) {
  46020. var sprite = this.sprites[index];
  46021. if (!sprite) {
  46022. continue;
  46023. }
  46024. sprite._animate(deltaTime);
  46025. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46026. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46027. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46028. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46029. }
  46030. this._buffer.update(this._vertexData);
  46031. // Render
  46032. var effect = this._effectBase;
  46033. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46034. effect = this._effectFog;
  46035. }
  46036. engine.enableEffect(effect);
  46037. var viewMatrix = this._scene.getViewMatrix();
  46038. effect.setTexture("diffuseSampler", this._spriteTexture);
  46039. effect.setMatrix("view", viewMatrix);
  46040. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46041. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46042. // Fog
  46043. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46044. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46045. effect.setColor3("vFogColor", this._scene.fogColor);
  46046. }
  46047. // VBOs
  46048. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46049. // Draw order
  46050. engine.setDepthFunctionToLessOrEqual();
  46051. effect.setBool("alphaTest", true);
  46052. engine.setColorWrite(false);
  46053. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46054. engine.setColorWrite(true);
  46055. effect.setBool("alphaTest", false);
  46056. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46057. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46058. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46059. };
  46060. SpriteManager.prototype.dispose = function () {
  46061. if (this._buffer) {
  46062. this._buffer.dispose();
  46063. this._buffer = null;
  46064. }
  46065. if (this._indexBuffer) {
  46066. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46067. this._indexBuffer = null;
  46068. }
  46069. if (this._spriteTexture) {
  46070. this._spriteTexture.dispose();
  46071. this._spriteTexture = null;
  46072. }
  46073. // Remove from scene
  46074. var index = this._scene.spriteManagers.indexOf(this);
  46075. this._scene.spriteManagers.splice(index, 1);
  46076. // Callback
  46077. this.onDisposeObservable.notifyObservers(this);
  46078. this.onDisposeObservable.clear();
  46079. };
  46080. return SpriteManager;
  46081. }());
  46082. BABYLON.SpriteManager = SpriteManager;
  46083. })(BABYLON || (BABYLON = {}));
  46084. //# sourceMappingURL=babylon.spriteManager.js.map
  46085. var BABYLON;
  46086. (function (BABYLON) {
  46087. var Sprite = /** @class */ (function () {
  46088. function Sprite(name, manager) {
  46089. this.name = name;
  46090. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46091. this.width = 1.0;
  46092. this.height = 1.0;
  46093. this.angle = 0;
  46094. this.cellIndex = 0;
  46095. this.invertU = 0;
  46096. this.invertV = 0;
  46097. this.animations = new Array();
  46098. this.isPickable = false;
  46099. this._animationStarted = false;
  46100. this._loopAnimation = false;
  46101. this._fromIndex = 0;
  46102. this._toIndex = 0;
  46103. this._delay = 0;
  46104. this._direction = 1;
  46105. this._time = 0;
  46106. this._manager = manager;
  46107. this._manager.sprites.push(this);
  46108. this.position = BABYLON.Vector3.Zero();
  46109. }
  46110. Object.defineProperty(Sprite.prototype, "size", {
  46111. get: function () {
  46112. return this.width;
  46113. },
  46114. set: function (value) {
  46115. this.width = value;
  46116. this.height = value;
  46117. },
  46118. enumerable: true,
  46119. configurable: true
  46120. });
  46121. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46122. this._fromIndex = from;
  46123. this._toIndex = to;
  46124. this._loopAnimation = loop;
  46125. this._delay = delay;
  46126. this._animationStarted = true;
  46127. this._direction = from < to ? 1 : -1;
  46128. this.cellIndex = from;
  46129. this._time = 0;
  46130. this._onAnimationEnd = onAnimationEnd;
  46131. };
  46132. Sprite.prototype.stopAnimation = function () {
  46133. this._animationStarted = false;
  46134. };
  46135. Sprite.prototype._animate = function (deltaTime) {
  46136. if (!this._animationStarted)
  46137. return;
  46138. this._time += deltaTime;
  46139. if (this._time > this._delay) {
  46140. this._time = this._time % this._delay;
  46141. this.cellIndex += this._direction;
  46142. if (this.cellIndex > this._toIndex) {
  46143. if (this._loopAnimation) {
  46144. this.cellIndex = this._fromIndex;
  46145. }
  46146. else {
  46147. this.cellIndex = this._toIndex;
  46148. this._animationStarted = false;
  46149. if (this._onAnimationEnd) {
  46150. this._onAnimationEnd();
  46151. }
  46152. if (this.disposeWhenFinishedAnimating) {
  46153. this.dispose();
  46154. }
  46155. }
  46156. }
  46157. }
  46158. };
  46159. Sprite.prototype.dispose = function () {
  46160. for (var i = 0; i < this._manager.sprites.length; i++) {
  46161. if (this._manager.sprites[i] == this) {
  46162. this._manager.sprites.splice(i, 1);
  46163. }
  46164. }
  46165. };
  46166. return Sprite;
  46167. }());
  46168. BABYLON.Sprite = Sprite;
  46169. })(BABYLON || (BABYLON = {}));
  46170. //# sourceMappingURL=babylon.sprite.js.map
  46171. var BABYLON;
  46172. (function (BABYLON) {
  46173. var IntersectionInfo = /** @class */ (function () {
  46174. function IntersectionInfo(bu, bv, distance) {
  46175. this.bu = bu;
  46176. this.bv = bv;
  46177. this.distance = distance;
  46178. this.faceId = 0;
  46179. this.subMeshId = 0;
  46180. }
  46181. return IntersectionInfo;
  46182. }());
  46183. BABYLON.IntersectionInfo = IntersectionInfo;
  46184. var PickingInfo = /** @class */ (function () {
  46185. function PickingInfo() {
  46186. this.hit = false;
  46187. this.distance = 0;
  46188. this.pickedPoint = null;
  46189. this.pickedMesh = null;
  46190. this.bu = 0;
  46191. this.bv = 0;
  46192. this.faceId = -1;
  46193. this.subMeshId = 0;
  46194. this.pickedSprite = null;
  46195. }
  46196. // Methods
  46197. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  46198. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  46199. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  46200. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46201. return null;
  46202. }
  46203. var indices = this.pickedMesh.getIndices();
  46204. if (!indices) {
  46205. return null;
  46206. }
  46207. var result;
  46208. if (useVerticesNormals) {
  46209. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46210. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  46211. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  46212. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  46213. normal0 = normal0.scale(this.bu);
  46214. normal1 = normal1.scale(this.bv);
  46215. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  46216. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  46217. }
  46218. else {
  46219. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46220. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  46221. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  46222. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  46223. var p1p2 = vertex1.subtract(vertex2);
  46224. var p3p2 = vertex3.subtract(vertex2);
  46225. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  46226. }
  46227. if (useWorldCoordinates) {
  46228. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  46229. }
  46230. return BABYLON.Vector3.Normalize(result);
  46231. };
  46232. PickingInfo.prototype.getTextureCoordinates = function () {
  46233. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46234. return null;
  46235. }
  46236. var indices = this.pickedMesh.getIndices();
  46237. if (!indices) {
  46238. return null;
  46239. }
  46240. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46241. if (!uvs) {
  46242. return null;
  46243. }
  46244. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  46245. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  46246. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  46247. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  46248. uv1 = uv1.scale(this.bu);
  46249. uv2 = uv2.scale(this.bv);
  46250. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  46251. };
  46252. return PickingInfo;
  46253. }());
  46254. BABYLON.PickingInfo = PickingInfo;
  46255. })(BABYLON || (BABYLON = {}));
  46256. //# sourceMappingURL=babylon.pickingInfo.js.map
  46257. var BABYLON;
  46258. (function (BABYLON) {
  46259. var Ray = /** @class */ (function () {
  46260. function Ray(origin, direction, length) {
  46261. if (length === void 0) { length = Number.MAX_VALUE; }
  46262. this.origin = origin;
  46263. this.direction = direction;
  46264. this.length = length;
  46265. }
  46266. // Methods
  46267. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  46268. var d = 0.0;
  46269. var maxValue = Number.MAX_VALUE;
  46270. var inv;
  46271. var min;
  46272. var max;
  46273. var temp;
  46274. if (Math.abs(this.direction.x) < 0.0000001) {
  46275. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  46276. return false;
  46277. }
  46278. }
  46279. else {
  46280. inv = 1.0 / this.direction.x;
  46281. min = (minimum.x - this.origin.x) * inv;
  46282. max = (maximum.x - this.origin.x) * inv;
  46283. if (max === -Infinity) {
  46284. max = Infinity;
  46285. }
  46286. if (min > max) {
  46287. temp = min;
  46288. min = max;
  46289. max = temp;
  46290. }
  46291. d = Math.max(min, d);
  46292. maxValue = Math.min(max, maxValue);
  46293. if (d > maxValue) {
  46294. return false;
  46295. }
  46296. }
  46297. if (Math.abs(this.direction.y) < 0.0000001) {
  46298. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  46299. return false;
  46300. }
  46301. }
  46302. else {
  46303. inv = 1.0 / this.direction.y;
  46304. min = (minimum.y - this.origin.y) * inv;
  46305. max = (maximum.y - this.origin.y) * inv;
  46306. if (max === -Infinity) {
  46307. max = Infinity;
  46308. }
  46309. if (min > max) {
  46310. temp = min;
  46311. min = max;
  46312. max = temp;
  46313. }
  46314. d = Math.max(min, d);
  46315. maxValue = Math.min(max, maxValue);
  46316. if (d > maxValue) {
  46317. return false;
  46318. }
  46319. }
  46320. if (Math.abs(this.direction.z) < 0.0000001) {
  46321. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  46322. return false;
  46323. }
  46324. }
  46325. else {
  46326. inv = 1.0 / this.direction.z;
  46327. min = (minimum.z - this.origin.z) * inv;
  46328. max = (maximum.z - this.origin.z) * inv;
  46329. if (max === -Infinity) {
  46330. max = Infinity;
  46331. }
  46332. if (min > max) {
  46333. temp = min;
  46334. min = max;
  46335. max = temp;
  46336. }
  46337. d = Math.max(min, d);
  46338. maxValue = Math.min(max, maxValue);
  46339. if (d > maxValue) {
  46340. return false;
  46341. }
  46342. }
  46343. return true;
  46344. };
  46345. Ray.prototype.intersectsBox = function (box) {
  46346. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  46347. };
  46348. Ray.prototype.intersectsSphere = function (sphere) {
  46349. var x = sphere.center.x - this.origin.x;
  46350. var y = sphere.center.y - this.origin.y;
  46351. var z = sphere.center.z - this.origin.z;
  46352. var pyth = (x * x) + (y * y) + (z * z);
  46353. var rr = sphere.radius * sphere.radius;
  46354. if (pyth <= rr) {
  46355. return true;
  46356. }
  46357. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  46358. if (dot < 0.0) {
  46359. return false;
  46360. }
  46361. var temp = pyth - (dot * dot);
  46362. return temp <= rr;
  46363. };
  46364. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  46365. if (!this._edge1) {
  46366. this._edge1 = BABYLON.Vector3.Zero();
  46367. this._edge2 = BABYLON.Vector3.Zero();
  46368. this._pvec = BABYLON.Vector3.Zero();
  46369. this._tvec = BABYLON.Vector3.Zero();
  46370. this._qvec = BABYLON.Vector3.Zero();
  46371. }
  46372. vertex1.subtractToRef(vertex0, this._edge1);
  46373. vertex2.subtractToRef(vertex0, this._edge2);
  46374. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46375. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46376. if (det === 0) {
  46377. return null;
  46378. }
  46379. var invdet = 1 / det;
  46380. this.origin.subtractToRef(vertex0, this._tvec);
  46381. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46382. if (bu < 0 || bu > 1.0) {
  46383. return null;
  46384. }
  46385. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46386. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46387. if (bv < 0 || bu + bv > 1.0) {
  46388. return null;
  46389. }
  46390. //check if the distance is longer than the predefined length.
  46391. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46392. if (distance > this.length) {
  46393. return null;
  46394. }
  46395. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46396. };
  46397. Ray.prototype.intersectsPlane = function (plane) {
  46398. var distance;
  46399. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46400. if (Math.abs(result1) < 9.99999997475243E-07) {
  46401. return null;
  46402. }
  46403. else {
  46404. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46405. distance = (-plane.d - result2) / result1;
  46406. if (distance < 0.0) {
  46407. if (distance < -9.99999997475243E-07) {
  46408. return null;
  46409. }
  46410. else {
  46411. return 0;
  46412. }
  46413. }
  46414. return distance;
  46415. }
  46416. };
  46417. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46418. var tm = BABYLON.Tmp.Matrix[0];
  46419. mesh.getWorldMatrix().invertToRef(tm);
  46420. if (this._tmpRay) {
  46421. Ray.TransformToRef(this, tm, this._tmpRay);
  46422. }
  46423. else {
  46424. this._tmpRay = Ray.Transform(this, tm);
  46425. }
  46426. return mesh.intersects(this._tmpRay, fastCheck);
  46427. };
  46428. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46429. if (results) {
  46430. results.length = 0;
  46431. }
  46432. else {
  46433. results = [];
  46434. }
  46435. for (var i = 0; i < meshes.length; i++) {
  46436. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46437. if (pickInfo.hit) {
  46438. results.push(pickInfo);
  46439. }
  46440. }
  46441. results.sort(this._comparePickingInfo);
  46442. return results;
  46443. };
  46444. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46445. if (pickingInfoA.distance < pickingInfoB.distance) {
  46446. return -1;
  46447. }
  46448. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46449. return 1;
  46450. }
  46451. else {
  46452. return 0;
  46453. }
  46454. };
  46455. /**
  46456. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46457. * @param sega the first point of the segment to test the intersection against
  46458. * @param segb the second point of the segment to test the intersection against
  46459. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46460. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46461. */
  46462. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46463. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46464. var u = segb.subtract(sega);
  46465. var v = rsegb.subtract(this.origin);
  46466. var w = sega.subtract(this.origin);
  46467. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46468. var b = BABYLON.Vector3.Dot(u, v);
  46469. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46470. var d = BABYLON.Vector3.Dot(u, w);
  46471. var e = BABYLON.Vector3.Dot(v, w);
  46472. var D = a * c - b * b; // always >= 0
  46473. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46474. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46475. // compute the line parameters of the two closest points
  46476. if (D < Ray.smallnum) {
  46477. sN = 0.0; // force using point P0 on segment S1
  46478. sD = 1.0; // to prevent possible division by 0.0 later
  46479. tN = e;
  46480. tD = c;
  46481. }
  46482. else {
  46483. sN = (b * e - c * d);
  46484. tN = (a * e - b * d);
  46485. if (sN < 0.0) {
  46486. sN = 0.0;
  46487. tN = e;
  46488. tD = c;
  46489. }
  46490. else if (sN > sD) {
  46491. sN = sD;
  46492. tN = e + b;
  46493. tD = c;
  46494. }
  46495. }
  46496. if (tN < 0.0) {
  46497. tN = 0.0;
  46498. // recompute sc for this edge
  46499. if (-d < 0.0) {
  46500. sN = 0.0;
  46501. }
  46502. else if (-d > a)
  46503. sN = sD;
  46504. else {
  46505. sN = -d;
  46506. sD = a;
  46507. }
  46508. }
  46509. else if (tN > tD) {
  46510. tN = tD;
  46511. // recompute sc for this edge
  46512. if ((-d + b) < 0.0) {
  46513. sN = 0;
  46514. }
  46515. else if ((-d + b) > a) {
  46516. sN = sD;
  46517. }
  46518. else {
  46519. sN = (-d + b);
  46520. sD = a;
  46521. }
  46522. }
  46523. // finally do the division to get sc and tc
  46524. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46525. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46526. // get the difference of the two closest points
  46527. var qtc = v.multiplyByFloats(tc, tc, tc);
  46528. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46529. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46530. if (isIntersected) {
  46531. return qtc.length();
  46532. }
  46533. return -1;
  46534. };
  46535. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46536. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46537. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46538. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46539. this.direction.normalize();
  46540. return this;
  46541. };
  46542. // Statics
  46543. Ray.Zero = function () {
  46544. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46545. };
  46546. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46547. var result = Ray.Zero();
  46548. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46549. };
  46550. /**
  46551. * 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
  46552. * transformed to the given world matrix.
  46553. * @param origin The origin point
  46554. * @param end The end point
  46555. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46556. */
  46557. Ray.CreateNewFromTo = function (origin, end, world) {
  46558. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46559. var direction = end.subtract(origin);
  46560. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46561. direction.normalize();
  46562. return Ray.Transform(new Ray(origin, direction, length), world);
  46563. };
  46564. Ray.Transform = function (ray, matrix) {
  46565. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46566. Ray.TransformToRef(ray, matrix, result);
  46567. return result;
  46568. };
  46569. Ray.TransformToRef = function (ray, matrix, result) {
  46570. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46571. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46572. result.length = ray.length;
  46573. var dir = result.direction;
  46574. var len = dir.length();
  46575. if (!(len === 0 || len === 1)) {
  46576. var num = 1.0 / len;
  46577. dir.x *= num;
  46578. dir.y *= num;
  46579. dir.z *= num;
  46580. result.length *= len;
  46581. }
  46582. };
  46583. Ray.smallnum = 0.00000001;
  46584. Ray.rayl = 10e8;
  46585. return Ray;
  46586. }());
  46587. BABYLON.Ray = Ray;
  46588. })(BABYLON || (BABYLON = {}));
  46589. //# sourceMappingURL=babylon.ray.js.map
  46590. var BABYLON;
  46591. (function (BABYLON) {
  46592. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46593. if (boxMin.x > sphereCenter.x + sphereRadius)
  46594. return false;
  46595. if (sphereCenter.x - sphereRadius > boxMax.x)
  46596. return false;
  46597. if (boxMin.y > sphereCenter.y + sphereRadius)
  46598. return false;
  46599. if (sphereCenter.y - sphereRadius > boxMax.y)
  46600. return false;
  46601. if (boxMin.z > sphereCenter.z + sphereRadius)
  46602. return false;
  46603. if (sphereCenter.z - sphereRadius > boxMax.z)
  46604. return false;
  46605. return true;
  46606. };
  46607. var getLowestRoot = (function () {
  46608. var result = { root: 0, found: false };
  46609. return function (a, b, c, maxR) {
  46610. result.root = 0;
  46611. result.found = false;
  46612. var determinant = b * b - 4.0 * a * c;
  46613. if (determinant < 0)
  46614. return result;
  46615. var sqrtD = Math.sqrt(determinant);
  46616. var r1 = (-b - sqrtD) / (2.0 * a);
  46617. var r2 = (-b + sqrtD) / (2.0 * a);
  46618. if (r1 > r2) {
  46619. var temp = r2;
  46620. r2 = r1;
  46621. r1 = temp;
  46622. }
  46623. if (r1 > 0 && r1 < maxR) {
  46624. result.root = r1;
  46625. result.found = true;
  46626. return result;
  46627. }
  46628. if (r2 > 0 && r2 < maxR) {
  46629. result.root = r2;
  46630. result.found = true;
  46631. return result;
  46632. }
  46633. return result;
  46634. };
  46635. })();
  46636. var Collider = /** @class */ (function () {
  46637. function Collider() {
  46638. this._collisionPoint = BABYLON.Vector3.Zero();
  46639. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  46640. this._tempVector = BABYLON.Vector3.Zero();
  46641. this._tempVector2 = BABYLON.Vector3.Zero();
  46642. this._tempVector3 = BABYLON.Vector3.Zero();
  46643. this._tempVector4 = BABYLON.Vector3.Zero();
  46644. this._edge = BABYLON.Vector3.Zero();
  46645. this._baseToVertex = BABYLON.Vector3.Zero();
  46646. this._destinationPoint = BABYLON.Vector3.Zero();
  46647. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  46648. this._displacementVector = BABYLON.Vector3.Zero();
  46649. this._radius = BABYLON.Vector3.One();
  46650. this._retry = 0;
  46651. this._basePointWorld = BABYLON.Vector3.Zero();
  46652. this._velocityWorld = BABYLON.Vector3.Zero();
  46653. this._normalizedVelocity = BABYLON.Vector3.Zero();
  46654. this._collisionMask = -1;
  46655. }
  46656. Object.defineProperty(Collider.prototype, "collisionMask", {
  46657. get: function () {
  46658. return this._collisionMask;
  46659. },
  46660. set: function (mask) {
  46661. this._collisionMask = !isNaN(mask) ? mask : -1;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  46667. /**
  46668. * Gets the plane normal used to compute the sliding response (in local space)
  46669. */
  46670. get: function () {
  46671. return this._slidePlaneNormal;
  46672. },
  46673. enumerable: true,
  46674. configurable: true
  46675. });
  46676. // Methods
  46677. Collider.prototype._initialize = function (source, dir, e) {
  46678. this._velocity = dir;
  46679. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  46680. this._basePoint = source;
  46681. source.multiplyToRef(this._radius, this._basePointWorld);
  46682. dir.multiplyToRef(this._radius, this._velocityWorld);
  46683. this._velocityWorldLength = this._velocityWorld.length();
  46684. this._epsilon = e;
  46685. this.collisionFound = false;
  46686. };
  46687. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  46688. pa.subtractToRef(point, this._tempVector);
  46689. pb.subtractToRef(point, this._tempVector2);
  46690. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  46691. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46692. if (d < 0)
  46693. return false;
  46694. pc.subtractToRef(point, this._tempVector3);
  46695. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  46696. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46697. if (d < 0)
  46698. return false;
  46699. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  46700. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46701. return d >= 0;
  46702. };
  46703. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  46704. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  46705. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  46706. if (distance > this._velocityWorldLength + max + sphereRadius) {
  46707. return false;
  46708. }
  46709. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  46710. return false;
  46711. return true;
  46712. };
  46713. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  46714. var t0;
  46715. var embeddedInPlane = false;
  46716. //defensive programming, actually not needed.
  46717. if (!trianglePlaneArray) {
  46718. trianglePlaneArray = [];
  46719. }
  46720. if (!trianglePlaneArray[faceIndex]) {
  46721. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  46722. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  46723. }
  46724. var trianglePlane = trianglePlaneArray[faceIndex];
  46725. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  46726. return;
  46727. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  46728. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  46729. if (normalDotVelocity == 0) {
  46730. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  46731. return;
  46732. embeddedInPlane = true;
  46733. t0 = 0;
  46734. }
  46735. else {
  46736. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46737. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46738. if (t0 > t1) {
  46739. var temp = t1;
  46740. t1 = t0;
  46741. t0 = temp;
  46742. }
  46743. if (t0 > 1.0 || t1 < 0.0)
  46744. return;
  46745. if (t0 < 0)
  46746. t0 = 0;
  46747. if (t0 > 1.0)
  46748. t0 = 1.0;
  46749. }
  46750. this._collisionPoint.copyFromFloats(0, 0, 0);
  46751. var found = false;
  46752. var t = 1.0;
  46753. if (!embeddedInPlane) {
  46754. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  46755. this._velocity.scaleToRef(t0, this._tempVector);
  46756. this._planeIntersectionPoint.addInPlace(this._tempVector);
  46757. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  46758. found = true;
  46759. t = t0;
  46760. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  46761. }
  46762. }
  46763. if (!found) {
  46764. var velocitySquaredLength = this._velocity.lengthSquared();
  46765. var a = velocitySquaredLength;
  46766. this._basePoint.subtractToRef(p1, this._tempVector);
  46767. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46768. var c = this._tempVector.lengthSquared() - 1.0;
  46769. var lowestRoot = getLowestRoot(a, b, c, t);
  46770. if (lowestRoot.found) {
  46771. t = lowestRoot.root;
  46772. found = true;
  46773. this._collisionPoint.copyFrom(p1);
  46774. }
  46775. this._basePoint.subtractToRef(p2, this._tempVector);
  46776. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46777. c = this._tempVector.lengthSquared() - 1.0;
  46778. lowestRoot = getLowestRoot(a, b, c, t);
  46779. if (lowestRoot.found) {
  46780. t = lowestRoot.root;
  46781. found = true;
  46782. this._collisionPoint.copyFrom(p2);
  46783. }
  46784. this._basePoint.subtractToRef(p3, this._tempVector);
  46785. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46786. c = this._tempVector.lengthSquared() - 1.0;
  46787. lowestRoot = getLowestRoot(a, b, c, t);
  46788. if (lowestRoot.found) {
  46789. t = lowestRoot.root;
  46790. found = true;
  46791. this._collisionPoint.copyFrom(p3);
  46792. }
  46793. p2.subtractToRef(p1, this._edge);
  46794. p1.subtractToRef(this._basePoint, this._baseToVertex);
  46795. var edgeSquaredLength = this._edge.lengthSquared();
  46796. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46797. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46798. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46799. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46800. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46801. lowestRoot = getLowestRoot(a, b, c, t);
  46802. if (lowestRoot.found) {
  46803. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46804. if (f >= 0.0 && f <= 1.0) {
  46805. t = lowestRoot.root;
  46806. found = true;
  46807. this._edge.scaleInPlace(f);
  46808. p1.addToRef(this._edge, this._collisionPoint);
  46809. }
  46810. }
  46811. p3.subtractToRef(p2, this._edge);
  46812. p2.subtractToRef(this._basePoint, this._baseToVertex);
  46813. edgeSquaredLength = this._edge.lengthSquared();
  46814. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46815. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46816. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46817. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46818. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46819. lowestRoot = getLowestRoot(a, b, c, t);
  46820. if (lowestRoot.found) {
  46821. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46822. if (f >= 0.0 && f <= 1.0) {
  46823. t = lowestRoot.root;
  46824. found = true;
  46825. this._edge.scaleInPlace(f);
  46826. p2.addToRef(this._edge, this._collisionPoint);
  46827. }
  46828. }
  46829. p1.subtractToRef(p3, this._edge);
  46830. p3.subtractToRef(this._basePoint, this._baseToVertex);
  46831. edgeSquaredLength = this._edge.lengthSquared();
  46832. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46833. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46834. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46835. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46836. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46837. lowestRoot = getLowestRoot(a, b, c, t);
  46838. if (lowestRoot.found) {
  46839. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46840. if (f >= 0.0 && f <= 1.0) {
  46841. t = lowestRoot.root;
  46842. found = true;
  46843. this._edge.scaleInPlace(f);
  46844. p3.addToRef(this._edge, this._collisionPoint);
  46845. }
  46846. }
  46847. }
  46848. if (found) {
  46849. var distToCollision = t * this._velocity.length();
  46850. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  46851. if (!this.intersectionPoint) {
  46852. this.intersectionPoint = this._collisionPoint.clone();
  46853. }
  46854. else {
  46855. this.intersectionPoint.copyFrom(this._collisionPoint);
  46856. }
  46857. this._nearestDistance = distToCollision;
  46858. this.collisionFound = true;
  46859. }
  46860. }
  46861. };
  46862. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  46863. for (var i = indexStart; i < indexEnd; i += 3) {
  46864. var p1 = pts[indices[i] - decal];
  46865. var p2 = pts[indices[i + 1] - decal];
  46866. var p3 = pts[indices[i + 2] - decal];
  46867. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  46868. }
  46869. };
  46870. Collider.prototype._getResponse = function (pos, vel) {
  46871. pos.addToRef(vel, this._destinationPoint);
  46872. vel.scaleInPlace((this._nearestDistance / vel.length()));
  46873. this._basePoint.addToRef(vel, pos);
  46874. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  46875. this._slidePlaneNormal.normalize();
  46876. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  46877. pos.addInPlace(this._displacementVector);
  46878. this.intersectionPoint.addInPlace(this._displacementVector);
  46879. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  46880. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  46881. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  46882. };
  46883. return Collider;
  46884. }());
  46885. BABYLON.Collider = Collider;
  46886. })(BABYLON || (BABYLON = {}));
  46887. //# sourceMappingURL=babylon.collider.js.map
  46888. var BABYLON;
  46889. (function (BABYLON) {
  46890. //WebWorker code will be inserted to this variable.
  46891. BABYLON.CollisionWorker = "";
  46892. var WorkerTaskType;
  46893. (function (WorkerTaskType) {
  46894. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  46895. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  46896. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  46897. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  46898. var WorkerReplyType;
  46899. (function (WorkerReplyType) {
  46900. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  46901. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  46902. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  46903. var CollisionCoordinatorWorker = /** @class */ (function () {
  46904. function CollisionCoordinatorWorker() {
  46905. var _this = this;
  46906. this._scaledPosition = BABYLON.Vector3.Zero();
  46907. this._scaledVelocity = BABYLON.Vector3.Zero();
  46908. this.onMeshUpdated = function (transformNode) {
  46909. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  46910. };
  46911. this.onGeometryUpdated = function (geometry) {
  46912. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  46913. };
  46914. this._afterRender = function () {
  46915. if (!_this._init)
  46916. return;
  46917. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  46918. return;
  46919. }
  46920. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  46921. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  46922. if (_this._runningUpdated > 4) {
  46923. return;
  46924. }
  46925. ++_this._runningUpdated;
  46926. var payload = {
  46927. updatedMeshes: _this._addUpdateMeshesList,
  46928. updatedGeometries: _this._addUpdateGeometriesList,
  46929. removedGeometries: _this._toRemoveGeometryArray,
  46930. removedMeshes: _this._toRemoveMeshesArray
  46931. };
  46932. var message = {
  46933. payload: payload,
  46934. taskType: WorkerTaskType.UPDATE
  46935. };
  46936. var serializable = [];
  46937. for (var id in payload.updatedGeometries) {
  46938. if (payload.updatedGeometries.hasOwnProperty(id)) {
  46939. //prepare transferables
  46940. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  46941. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  46942. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  46943. }
  46944. }
  46945. _this._worker.postMessage(message, serializable);
  46946. _this._addUpdateMeshesList = {};
  46947. _this._addUpdateGeometriesList = {};
  46948. _this._toRemoveGeometryArray = [];
  46949. _this._toRemoveMeshesArray = [];
  46950. };
  46951. this._onMessageFromWorker = function (e) {
  46952. var returnData = e.data;
  46953. if (returnData.error != WorkerReplyType.SUCCESS) {
  46954. //TODO what errors can be returned from the worker?
  46955. BABYLON.Tools.Warn("error returned from worker!");
  46956. return;
  46957. }
  46958. switch (returnData.taskType) {
  46959. case WorkerTaskType.INIT:
  46960. _this._init = true;
  46961. //Update the worked with ALL of the scene's current state
  46962. _this._scene.meshes.forEach(function (mesh) {
  46963. _this.onMeshAdded(mesh);
  46964. });
  46965. _this._scene.getGeometries().forEach(function (geometry) {
  46966. _this.onGeometryAdded(geometry);
  46967. });
  46968. break;
  46969. case WorkerTaskType.UPDATE:
  46970. _this._runningUpdated--;
  46971. break;
  46972. case WorkerTaskType.COLLIDE:
  46973. var returnPayload = returnData.payload;
  46974. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  46975. return;
  46976. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  46977. if (callback) {
  46978. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  46979. if (mesh) {
  46980. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  46981. }
  46982. }
  46983. //cleanup
  46984. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  46985. break;
  46986. }
  46987. };
  46988. this._collisionsCallbackArray = [];
  46989. this._init = false;
  46990. this._runningUpdated = 0;
  46991. this._addUpdateMeshesList = {};
  46992. this._addUpdateGeometriesList = {};
  46993. this._toRemoveGeometryArray = [];
  46994. this._toRemoveMeshesArray = [];
  46995. }
  46996. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46997. if (!this._init)
  46998. return;
  46999. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47000. return;
  47001. position.divideToRef(collider._radius, this._scaledPosition);
  47002. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47003. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47004. var payload = {
  47005. collider: {
  47006. position: this._scaledPosition.asArray(),
  47007. velocity: this._scaledVelocity.asArray(),
  47008. radius: collider._radius.asArray()
  47009. },
  47010. collisionId: collisionIndex,
  47011. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47012. maximumRetry: maximumRetry
  47013. };
  47014. var message = {
  47015. payload: payload,
  47016. taskType: WorkerTaskType.COLLIDE
  47017. };
  47018. this._worker.postMessage(message);
  47019. };
  47020. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47021. this._scene = scene;
  47022. this._scene.registerAfterRender(this._afterRender);
  47023. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47024. this._worker = new Worker(workerUrl);
  47025. this._worker.onmessage = this._onMessageFromWorker;
  47026. var message = {
  47027. payload: {},
  47028. taskType: WorkerTaskType.INIT
  47029. };
  47030. this._worker.postMessage(message);
  47031. };
  47032. CollisionCoordinatorWorker.prototype.destroy = function () {
  47033. this._scene.unregisterAfterRender(this._afterRender);
  47034. this._worker.terminate();
  47035. };
  47036. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47037. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47038. this.onMeshUpdated(mesh);
  47039. };
  47040. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47041. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47042. };
  47043. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47044. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47045. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47046. this.onGeometryUpdated(geometry);
  47047. };
  47048. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47049. this._toRemoveGeometryArray.push(geometry.id);
  47050. };
  47051. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47052. var submeshes = [];
  47053. if (mesh.subMeshes) {
  47054. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47055. var boundingInfo = sm.getBoundingInfo();
  47056. return {
  47057. position: idx,
  47058. verticesStart: sm.verticesStart,
  47059. verticesCount: sm.verticesCount,
  47060. indexStart: sm.indexStart,
  47061. indexCount: sm.indexCount,
  47062. hasMaterial: !!sm.getMaterial(),
  47063. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47064. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47065. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47066. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47067. };
  47068. });
  47069. }
  47070. var geometryId = null;
  47071. if (mesh instanceof BABYLON.Mesh) {
  47072. var geometry = mesh.geometry;
  47073. geometryId = geometry ? geometry.id : null;
  47074. }
  47075. else if (mesh instanceof BABYLON.InstancedMesh) {
  47076. var geometry = mesh.sourceMesh.geometry;
  47077. geometryId = geometry ? geometry.id : null;
  47078. }
  47079. var boundingInfo = mesh.getBoundingInfo();
  47080. return {
  47081. uniqueId: mesh.uniqueId,
  47082. id: mesh.id,
  47083. name: mesh.name,
  47084. geometryId: geometryId,
  47085. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47086. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47087. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47088. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47089. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47090. subMeshes: submeshes,
  47091. checkCollisions: mesh.checkCollisions
  47092. };
  47093. };
  47094. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47095. return {
  47096. id: geometry.id,
  47097. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47098. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47099. indices: new Uint32Array(geometry.getIndices() || []),
  47100. };
  47101. };
  47102. return CollisionCoordinatorWorker;
  47103. }());
  47104. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47105. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47106. function CollisionCoordinatorLegacy() {
  47107. this._scaledPosition = BABYLON.Vector3.Zero();
  47108. this._scaledVelocity = BABYLON.Vector3.Zero();
  47109. this._finalPosition = BABYLON.Vector3.Zero();
  47110. }
  47111. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47112. position.divideToRef(collider._radius, this._scaledPosition);
  47113. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47114. collider.collidedMesh = null;
  47115. collider._retry = 0;
  47116. collider._initialVelocity = this._scaledVelocity;
  47117. collider._initialPosition = this._scaledPosition;
  47118. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47119. this._finalPosition.multiplyInPlace(collider._radius);
  47120. //run the callback
  47121. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47122. };
  47123. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47124. this._scene = scene;
  47125. };
  47126. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47127. //Legacy need no destruction method.
  47128. };
  47129. //No update in legacy mode
  47130. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  47131. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  47132. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  47133. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  47134. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  47135. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  47136. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  47137. if (excludedMesh === void 0) { excludedMesh = null; }
  47138. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  47139. if (collider._retry >= maximumRetry) {
  47140. finalPosition.copyFrom(position);
  47141. return;
  47142. }
  47143. // Check if this is a mesh else camera or -1
  47144. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  47145. collider._initialize(position, velocity, closeDistance);
  47146. // Check all meshes
  47147. for (var index = 0; index < this._scene.meshes.length; index++) {
  47148. var mesh = this._scene.meshes[index];
  47149. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  47150. mesh._checkCollision(collider);
  47151. }
  47152. }
  47153. if (!collider.collisionFound) {
  47154. position.addToRef(velocity, finalPosition);
  47155. return;
  47156. }
  47157. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  47158. collider._getResponse(position, velocity);
  47159. }
  47160. if (velocity.length() <= closeDistance) {
  47161. finalPosition.copyFrom(position);
  47162. return;
  47163. }
  47164. collider._retry++;
  47165. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  47166. };
  47167. return CollisionCoordinatorLegacy;
  47168. }());
  47169. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  47170. })(BABYLON || (BABYLON = {}));
  47171. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  47172. var BABYLON;
  47173. (function (BABYLON) {
  47174. /**
  47175. * A particle represents one of the element emitted by a particle system.
  47176. * This is mainly define by its coordinates, direction, velocity and age.
  47177. */
  47178. var Particle = /** @class */ (function () {
  47179. /**
  47180. * Creates a new instance of @see Particle
  47181. * @param particleSystem the particle system the particle belongs to
  47182. */
  47183. function Particle(particleSystem) {
  47184. this.particleSystem = particleSystem;
  47185. /**
  47186. * The world position of the particle in the scene.
  47187. */
  47188. this.position = BABYLON.Vector3.Zero();
  47189. /**
  47190. * The world direction of the particle in the scene.
  47191. */
  47192. this.direction = BABYLON.Vector3.Zero();
  47193. /**
  47194. * The color of the particle.
  47195. */
  47196. this.color = new BABYLON.Color4(0, 0, 0, 0);
  47197. /**
  47198. * The color change of the particle per step.
  47199. */
  47200. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  47201. /**
  47202. * Defines how long will the life of the particle be.
  47203. */
  47204. this.lifeTime = 1.0;
  47205. /**
  47206. * The current age of the particle.
  47207. */
  47208. this.age = 0;
  47209. /**
  47210. * The current size of the particle.
  47211. */
  47212. this.size = 0;
  47213. /**
  47214. * The current angle of the particle.
  47215. */
  47216. this.angle = 0;
  47217. /**
  47218. * Defines how fast is the angle changing.
  47219. */
  47220. this.angularSpeed = 0;
  47221. /**
  47222. * Defines the cell index used by the particle to be rendered from a sprite.
  47223. */
  47224. this.cellIndex = 0;
  47225. this._currentFrameCounter = 0;
  47226. if (!this.particleSystem.isAnimationSheetEnabled) {
  47227. return;
  47228. }
  47229. this.cellIndex = this.particleSystem.startSpriteCellID;
  47230. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  47231. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  47232. }
  47233. else {
  47234. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  47235. }
  47236. }
  47237. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  47238. // (ageOffset / scaledUpdateSpeed) / available cells
  47239. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  47240. this._currentFrameCounter += scaledUpdateSpeed;
  47241. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  47242. this._currentFrameCounter = 0;
  47243. this.cellIndex++;
  47244. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47245. this.cellIndex = this.particleSystem.endSpriteCellID;
  47246. }
  47247. }
  47248. };
  47249. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  47250. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  47251. this.cellIndex++;
  47252. this._currentFrameCounter = 0;
  47253. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47254. if (this.particleSystem.spriteCellLoop) {
  47255. this.cellIndex = this.particleSystem.startSpriteCellID;
  47256. }
  47257. else {
  47258. this.cellIndex = this.particleSystem.endSpriteCellID;
  47259. }
  47260. }
  47261. }
  47262. else {
  47263. this._currentFrameCounter++;
  47264. }
  47265. };
  47266. /**
  47267. * Copy the properties of particle to another one.
  47268. * @param other the particle to copy the information to.
  47269. */
  47270. Particle.prototype.copyTo = function (other) {
  47271. other.position.copyFrom(this.position);
  47272. other.direction.copyFrom(this.direction);
  47273. other.color.copyFrom(this.color);
  47274. other.colorStep.copyFrom(this.colorStep);
  47275. other.lifeTime = this.lifeTime;
  47276. other.age = this.age;
  47277. other.size = this.size;
  47278. other.angle = this.angle;
  47279. other.angularSpeed = this.angularSpeed;
  47280. other.particleSystem = this.particleSystem;
  47281. other.cellIndex = this.cellIndex;
  47282. };
  47283. return Particle;
  47284. }());
  47285. BABYLON.Particle = Particle;
  47286. })(BABYLON || (BABYLON = {}));
  47287. //# sourceMappingURL=babylon.particle.js.map
  47288. var BABYLON;
  47289. (function (BABYLON) {
  47290. /**
  47291. * This represents a particle system in Babylon.
  47292. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47293. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  47294. * @example https://doc.babylonjs.com/babylon101/particles
  47295. */
  47296. var ParticleSystem = /** @class */ (function () {
  47297. /**
  47298. * Instantiates a particle system.
  47299. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47300. * @param name The name of the particle system
  47301. * @param capacity The max number of particles alive at the same time
  47302. * @param scene The scene the particle system belongs to
  47303. * @param customEffect a custom effect used to change the way particles are rendered by default
  47304. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  47305. * @param epsilon Offset used to render the particles
  47306. */
  47307. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  47308. if (customEffect === void 0) { customEffect = null; }
  47309. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  47310. if (epsilon === void 0) { epsilon = 0.01; }
  47311. var _this = this;
  47312. /**
  47313. * List of animations used by the particle system.
  47314. */
  47315. this.animations = [];
  47316. /**
  47317. * The rendering group used by the Particle system to chose when to render.
  47318. */
  47319. this.renderingGroupId = 0;
  47320. /**
  47321. * The emitter represents the Mesh or position we are attaching the particle system to.
  47322. */
  47323. this.emitter = null;
  47324. /**
  47325. * The density of particles, the rate of particle flow
  47326. */
  47327. this.emitRate = 10;
  47328. /**
  47329. * If you want to launch only a few particles at once, that can be done, as well.
  47330. */
  47331. this.manualEmitCount = -1;
  47332. /**
  47333. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47334. */
  47335. this.updateSpeed = 0.01;
  47336. /**
  47337. * The amount of time the particle system is running (depends of the overall speed above).
  47338. */
  47339. this.targetStopDuration = 0;
  47340. /**
  47341. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  47342. */
  47343. this.disposeOnStop = false;
  47344. /**
  47345. * Minimum power of emitting particles.
  47346. */
  47347. this.minEmitPower = 1;
  47348. /**
  47349. * Maximum power of emitting particles.
  47350. */
  47351. this.maxEmitPower = 1;
  47352. /**
  47353. * Minimum life time of emitting particles.
  47354. */
  47355. this.minLifeTime = 1;
  47356. /**
  47357. * Maximum life time of emitting particles.
  47358. */
  47359. this.maxLifeTime = 1;
  47360. /**
  47361. * Minimum Size of emitting particles.
  47362. */
  47363. this.minSize = 1;
  47364. /**
  47365. * Maximum Size of emitting particles.
  47366. */
  47367. this.maxSize = 1;
  47368. /**
  47369. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  47370. */
  47371. this.minAngularSpeed = 0;
  47372. /**
  47373. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  47374. */
  47375. this.maxAngularSpeed = 0;
  47376. /**
  47377. * The layer mask we are rendering the particles through.
  47378. */
  47379. this.layerMask = 0x0FFFFFFF;
  47380. /**
  47381. * This can help using your own shader to render the particle system.
  47382. * The according effect will be created
  47383. */
  47384. this.customShader = null;
  47385. /**
  47386. * By default particle system starts as soon as they are created. This prevents the
  47387. * automatic start to happen and let you decide when to start emitting particles.
  47388. */
  47389. this.preventAutoStart = false;
  47390. /**
  47391. * Callback triggered when the particle animation is ending.
  47392. */
  47393. this.onAnimationEnd = null;
  47394. /**
  47395. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47396. */
  47397. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47398. /**
  47399. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47400. * to override the particles.
  47401. */
  47402. this.forceDepthWrite = false;
  47403. /**
  47404. * You can use gravity if you want to give an orientation to your particles.
  47405. */
  47406. this.gravity = BABYLON.Vector3.Zero();
  47407. /**
  47408. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47409. */
  47410. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47411. /**
  47412. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47413. */
  47414. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47415. /**
  47416. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47417. */
  47418. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47419. /**
  47420. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47421. */
  47422. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47423. /**
  47424. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47425. */
  47426. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47427. /**
  47428. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47429. */
  47430. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47431. /**
  47432. * Color the particle will have at the end of its lifetime.
  47433. */
  47434. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47435. /**
  47436. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47437. */
  47438. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47439. /**
  47440. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47441. */
  47442. this.spriteCellLoop = true;
  47443. /**
  47444. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47445. */
  47446. this.spriteCellChangeSpeed = 0;
  47447. /**
  47448. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47449. */
  47450. this.startSpriteCellID = 0;
  47451. /**
  47452. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47453. */
  47454. this.endSpriteCellID = 0;
  47455. /**
  47456. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47457. */
  47458. this.spriteCellWidth = 0;
  47459. /**
  47460. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47461. */
  47462. this.spriteCellHeight = 0;
  47463. /**
  47464. * An event triggered when the system is disposed.
  47465. */
  47466. this.onDisposeObservable = new BABYLON.Observable();
  47467. this._particles = new Array();
  47468. this._stockParticles = new Array();
  47469. this._newPartsExcess = 0;
  47470. this._vertexBuffers = {};
  47471. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47472. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47473. this._scaledDirection = BABYLON.Vector3.Zero();
  47474. this._scaledGravity = BABYLON.Vector3.Zero();
  47475. this._currentRenderId = -1;
  47476. this._started = false;
  47477. this._stopped = false;
  47478. this._actualFrame = 0;
  47479. this._vertexBufferSize = 11;
  47480. this._appendParticleVertexes = null;
  47481. this.id = name;
  47482. this.name = name;
  47483. this._capacity = capacity;
  47484. this._epsilon = epsilon;
  47485. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47486. if (isAnimationSheetEnabled) {
  47487. this._vertexBufferSize = 12;
  47488. }
  47489. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47490. this._customEffect = customEffect;
  47491. scene.particleSystems.push(this);
  47492. this._createIndexBuffer();
  47493. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47494. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47495. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47496. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47497. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47498. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47499. if (this._isAnimationSheetEnabled) {
  47500. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47501. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47502. }
  47503. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47504. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47505. this._vertexBuffers["options"] = options;
  47506. // Default behaviors
  47507. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47508. this.updateFunction = function (particles) {
  47509. for (var index = 0; index < particles.length; index++) {
  47510. var particle = particles[index];
  47511. particle.age += _this._scaledUpdateSpeed;
  47512. if (particle.age >= particle.lifeTime) {
  47513. _this.recycleParticle(particle);
  47514. index--;
  47515. continue;
  47516. }
  47517. else {
  47518. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47519. particle.color.addInPlace(_this._scaledColorStep);
  47520. if (particle.color.a < 0)
  47521. particle.color.a = 0;
  47522. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47523. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47524. particle.position.addInPlace(_this._scaledDirection);
  47525. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47526. particle.direction.addInPlace(_this._scaledGravity);
  47527. if (_this._isAnimationSheetEnabled) {
  47528. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47529. }
  47530. }
  47531. }
  47532. };
  47533. }
  47534. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47535. /**
  47536. * Sets a callback that will be triggered when the system is disposed.
  47537. */
  47538. set: function (callback) {
  47539. if (this._onDisposeObserver) {
  47540. this.onDisposeObservable.remove(this._onDisposeObserver);
  47541. }
  47542. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47543. },
  47544. enumerable: true,
  47545. configurable: true
  47546. });
  47547. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47548. /**
  47549. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47550. */
  47551. get: function () {
  47552. return this._isAnimationSheetEnabled;
  47553. },
  47554. enumerable: true,
  47555. configurable: true
  47556. });
  47557. ParticleSystem.prototype._createIndexBuffer = function () {
  47558. var indices = [];
  47559. var index = 0;
  47560. for (var count = 0; count < this._capacity; count++) {
  47561. indices.push(index);
  47562. indices.push(index + 1);
  47563. indices.push(index + 2);
  47564. indices.push(index);
  47565. indices.push(index + 2);
  47566. indices.push(index + 3);
  47567. index += 4;
  47568. }
  47569. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47570. };
  47571. /**
  47572. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47573. * Its lifetime will start back at 0.
  47574. * @param particle The particle to recycle
  47575. */
  47576. ParticleSystem.prototype.recycleParticle = function (particle) {
  47577. var lastParticle = this._particles.pop();
  47578. if (lastParticle !== particle) {
  47579. lastParticle.copyTo(particle);
  47580. this._stockParticles.push(lastParticle);
  47581. }
  47582. };
  47583. /**
  47584. * Gets the maximum number of particles active at the same time.
  47585. * @returns The max number of active particles.
  47586. */
  47587. ParticleSystem.prototype.getCapacity = function () {
  47588. return this._capacity;
  47589. };
  47590. /**
  47591. * Gets Wether there are still active particles in the system.
  47592. * @returns True if it is alive, otherwise false.
  47593. */
  47594. ParticleSystem.prototype.isAlive = function () {
  47595. return this._alive;
  47596. };
  47597. /**
  47598. * Gets Wether the system has been started.
  47599. * @returns True if it has been started, otherwise false.
  47600. */
  47601. ParticleSystem.prototype.isStarted = function () {
  47602. return this._started;
  47603. };
  47604. /**
  47605. * Starts the particle system and begins to emit.
  47606. */
  47607. ParticleSystem.prototype.start = function () {
  47608. this._started = true;
  47609. this._stopped = false;
  47610. this._actualFrame = 0;
  47611. };
  47612. /**
  47613. * Stops the particle system.
  47614. */
  47615. ParticleSystem.prototype.stop = function () {
  47616. this._stopped = true;
  47617. };
  47618. /**
  47619. * @ignore (for internal use only)
  47620. */
  47621. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47622. var offset = index * this._vertexBufferSize;
  47623. this._vertexData[offset] = particle.position.x;
  47624. this._vertexData[offset + 1] = particle.position.y;
  47625. this._vertexData[offset + 2] = particle.position.z;
  47626. this._vertexData[offset + 3] = particle.color.r;
  47627. this._vertexData[offset + 4] = particle.color.g;
  47628. this._vertexData[offset + 5] = particle.color.b;
  47629. this._vertexData[offset + 6] = particle.color.a;
  47630. this._vertexData[offset + 7] = particle.angle;
  47631. this._vertexData[offset + 8] = particle.size;
  47632. this._vertexData[offset + 9] = offsetX;
  47633. this._vertexData[offset + 10] = offsetY;
  47634. };
  47635. /**
  47636. * @ignore (for internal use only)
  47637. */
  47638. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  47639. if (offsetX === 0)
  47640. offsetX = this._epsilon;
  47641. else if (offsetX === 1)
  47642. offsetX = 1 - this._epsilon;
  47643. if (offsetY === 0)
  47644. offsetY = this._epsilon;
  47645. else if (offsetY === 1)
  47646. offsetY = 1 - this._epsilon;
  47647. var offset = index * this._vertexBufferSize;
  47648. this._vertexData[offset] = particle.position.x;
  47649. this._vertexData[offset + 1] = particle.position.y;
  47650. this._vertexData[offset + 2] = particle.position.z;
  47651. this._vertexData[offset + 3] = particle.color.r;
  47652. this._vertexData[offset + 4] = particle.color.g;
  47653. this._vertexData[offset + 5] = particle.color.b;
  47654. this._vertexData[offset + 6] = particle.color.a;
  47655. this._vertexData[offset + 7] = particle.angle;
  47656. this._vertexData[offset + 8] = particle.size;
  47657. this._vertexData[offset + 9] = offsetX;
  47658. this._vertexData[offset + 10] = offsetY;
  47659. this._vertexData[offset + 11] = particle.cellIndex;
  47660. };
  47661. ParticleSystem.prototype._update = function (newParticles) {
  47662. // Update current
  47663. this._alive = this._particles.length > 0;
  47664. this.updateFunction(this._particles);
  47665. // Add new ones
  47666. var worldMatrix;
  47667. if (this.emitter.position) {
  47668. var emitterMesh = this.emitter;
  47669. worldMatrix = emitterMesh.getWorldMatrix();
  47670. }
  47671. else {
  47672. var emitterPosition = this.emitter;
  47673. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  47674. }
  47675. var particle;
  47676. for (var index = 0; index < newParticles; index++) {
  47677. if (this._particles.length === this._capacity) {
  47678. break;
  47679. }
  47680. if (this._stockParticles.length !== 0) {
  47681. particle = this._stockParticles.pop();
  47682. particle.age = 0;
  47683. particle.cellIndex = this.startSpriteCellID;
  47684. }
  47685. else {
  47686. particle = new BABYLON.Particle(this);
  47687. }
  47688. this._particles.push(particle);
  47689. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  47690. if (this.startPositionFunction) {
  47691. this.startPositionFunction(worldMatrix, particle.position, particle);
  47692. }
  47693. else {
  47694. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  47695. }
  47696. if (this.startDirectionFunction) {
  47697. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47698. }
  47699. else {
  47700. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47701. }
  47702. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  47703. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  47704. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  47705. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  47706. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  47707. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  47708. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  47709. }
  47710. };
  47711. ParticleSystem.prototype._getEffect = function () {
  47712. if (this._customEffect) {
  47713. return this._customEffect;
  47714. }
  47715. ;
  47716. var defines = [];
  47717. if (this._scene.clipPlane) {
  47718. defines.push("#define CLIPPLANE");
  47719. }
  47720. if (this._isAnimationSheetEnabled) {
  47721. defines.push("#define ANIMATESHEET");
  47722. }
  47723. // Effect
  47724. var join = defines.join("\n");
  47725. if (this._cachedDefines !== join) {
  47726. this._cachedDefines = join;
  47727. var attributesNamesOrOptions;
  47728. var effectCreationOption;
  47729. if (this._isAnimationSheetEnabled) {
  47730. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  47731. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  47732. }
  47733. else {
  47734. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  47735. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  47736. }
  47737. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  47738. }
  47739. return this._effect;
  47740. };
  47741. /**
  47742. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  47743. */
  47744. ParticleSystem.prototype.animate = function () {
  47745. if (!this._started)
  47746. return;
  47747. var effect = this._getEffect();
  47748. // Check
  47749. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  47750. return;
  47751. if (this._currentRenderId === this._scene.getRenderId()) {
  47752. return;
  47753. }
  47754. this._currentRenderId = this._scene.getRenderId();
  47755. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  47756. // determine the number of particles we need to create
  47757. var newParticles;
  47758. if (this.manualEmitCount > -1) {
  47759. newParticles = this.manualEmitCount;
  47760. this._newPartsExcess = 0;
  47761. this.manualEmitCount = 0;
  47762. }
  47763. else {
  47764. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  47765. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  47766. }
  47767. if (this._newPartsExcess > 1.0) {
  47768. newParticles += this._newPartsExcess >> 0;
  47769. this._newPartsExcess -= this._newPartsExcess >> 0;
  47770. }
  47771. this._alive = false;
  47772. if (!this._stopped) {
  47773. this._actualFrame += this._scaledUpdateSpeed;
  47774. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  47775. this.stop();
  47776. }
  47777. else {
  47778. newParticles = 0;
  47779. }
  47780. this._update(newParticles);
  47781. // Stopped?
  47782. if (this._stopped) {
  47783. if (!this._alive) {
  47784. this._started = false;
  47785. if (this.onAnimationEnd) {
  47786. this.onAnimationEnd();
  47787. }
  47788. if (this.disposeOnStop) {
  47789. this._scene._toBeDisposed.push(this);
  47790. }
  47791. }
  47792. }
  47793. // Animation sheet
  47794. if (this._isAnimationSheetEnabled) {
  47795. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  47796. }
  47797. else {
  47798. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  47799. }
  47800. // Update VBO
  47801. var offset = 0;
  47802. for (var index = 0; index < this._particles.length; index++) {
  47803. var particle = this._particles[index];
  47804. this._appendParticleVertexes(offset, particle);
  47805. offset += 4;
  47806. }
  47807. if (this._vertexBuffer) {
  47808. this._vertexBuffer.update(this._vertexData);
  47809. }
  47810. };
  47811. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  47812. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  47813. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  47814. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  47815. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  47816. };
  47817. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  47818. this._appendParticleVertex(offset++, particle, 0, 0);
  47819. this._appendParticleVertex(offset++, particle, 1, 0);
  47820. this._appendParticleVertex(offset++, particle, 1, 1);
  47821. this._appendParticleVertex(offset++, particle, 0, 1);
  47822. };
  47823. /**
  47824. * Rebuilds the particle system.
  47825. */
  47826. ParticleSystem.prototype.rebuild = function () {
  47827. this._createIndexBuffer();
  47828. if (this._vertexBuffer) {
  47829. this._vertexBuffer._rebuild();
  47830. }
  47831. };
  47832. /**
  47833. * Renders the particle system in its current state.
  47834. * @returns the current number of particles.
  47835. */
  47836. ParticleSystem.prototype.render = function () {
  47837. var effect = this._getEffect();
  47838. // Check
  47839. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  47840. return 0;
  47841. var engine = this._scene.getEngine();
  47842. // Render
  47843. engine.enableEffect(effect);
  47844. engine.setState(false);
  47845. var viewMatrix = this._scene.getViewMatrix();
  47846. effect.setTexture("diffuseSampler", this.particleTexture);
  47847. effect.setMatrix("view", viewMatrix);
  47848. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47849. if (this._isAnimationSheetEnabled) {
  47850. var baseSize = this.particleTexture.getBaseSize();
  47851. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  47852. }
  47853. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  47854. if (this._scene.clipPlane) {
  47855. var clipPlane = this._scene.clipPlane;
  47856. var invView = viewMatrix.clone();
  47857. invView.invert();
  47858. effect.setMatrix("invView", invView);
  47859. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  47860. }
  47861. // VBOs
  47862. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47863. // Draw order
  47864. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  47865. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  47866. }
  47867. else {
  47868. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47869. }
  47870. if (this.forceDepthWrite) {
  47871. engine.setDepthWrite(true);
  47872. }
  47873. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  47874. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47875. return this._particles.length;
  47876. };
  47877. /**
  47878. * Disposes the particle system and free the associated resources.
  47879. */
  47880. ParticleSystem.prototype.dispose = function () {
  47881. if (this._vertexBuffer) {
  47882. this._vertexBuffer.dispose();
  47883. this._vertexBuffer = null;
  47884. }
  47885. if (this._indexBuffer) {
  47886. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47887. this._indexBuffer = null;
  47888. }
  47889. if (this.particleTexture) {
  47890. this.particleTexture.dispose();
  47891. this.particleTexture = null;
  47892. }
  47893. // Remove from scene
  47894. var index = this._scene.particleSystems.indexOf(this);
  47895. if (index > -1) {
  47896. this._scene.particleSystems.splice(index, 1);
  47897. }
  47898. // Callback
  47899. this.onDisposeObservable.notifyObservers(this);
  47900. this.onDisposeObservable.clear();
  47901. };
  47902. /**
  47903. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  47904. * @param radius The radius of the sphere to emit from
  47905. * @returns the emitter
  47906. */
  47907. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  47908. if (radius === void 0) { radius = 1; }
  47909. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  47910. this.particleEmitterType = particleEmitter;
  47911. return particleEmitter;
  47912. };
  47913. /**
  47914. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  47915. * @param radius The radius of the sphere to emit from
  47916. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  47917. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  47918. * @returns the emitter
  47919. */
  47920. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  47921. if (radius === void 0) { radius = 1; }
  47922. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  47923. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  47924. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  47925. this.particleEmitterType = particleEmitter;
  47926. return particleEmitter;
  47927. };
  47928. /**
  47929. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  47930. * @param radius The radius of the cone to emit from
  47931. * @param angle The base angle of the cone
  47932. * @returns the emitter
  47933. */
  47934. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  47935. if (radius === void 0) { radius = 1; }
  47936. if (angle === void 0) { angle = Math.PI / 4; }
  47937. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  47938. this.particleEmitterType = particleEmitter;
  47939. return particleEmitter;
  47940. };
  47941. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  47942. /**
  47943. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  47944. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  47945. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  47946. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47947. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47948. * @returns the emitter
  47949. */
  47950. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  47951. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  47952. this.direction1 = direction1;
  47953. this.direction2 = direction2;
  47954. this.minEmitBox = minEmitBox;
  47955. this.maxEmitBox = maxEmitBox;
  47956. this.particleEmitterType = particleEmitter;
  47957. return particleEmitter;
  47958. };
  47959. /**
  47960. * Clones the particle system.
  47961. * @param name The name of the cloned object
  47962. * @param newEmitter The new emitter to use
  47963. * @returns the cloned particle system
  47964. */
  47965. ParticleSystem.prototype.clone = function (name, newEmitter) {
  47966. var custom = null;
  47967. var program = null;
  47968. if (this.customShader != null) {
  47969. program = this.customShader;
  47970. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  47971. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  47972. }
  47973. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  47974. result.customShader = program;
  47975. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  47976. if (newEmitter === undefined) {
  47977. newEmitter = this.emitter;
  47978. }
  47979. result.emitter = newEmitter;
  47980. if (this.particleTexture) {
  47981. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  47982. }
  47983. if (!this.preventAutoStart) {
  47984. result.start();
  47985. }
  47986. return result;
  47987. };
  47988. /**
  47989. * Serializes the particle system to a JSON object.
  47990. * @returns the JSON object
  47991. */
  47992. ParticleSystem.prototype.serialize = function () {
  47993. var serializationObject = {};
  47994. serializationObject.name = this.name;
  47995. serializationObject.id = this.id;
  47996. // Emitter
  47997. if (this.emitter.position) {
  47998. var emitterMesh = this.emitter;
  47999. serializationObject.emitterId = emitterMesh.id;
  48000. }
  48001. else {
  48002. var emitterPosition = this.emitter;
  48003. serializationObject.emitter = emitterPosition.asArray();
  48004. }
  48005. serializationObject.capacity = this.getCapacity();
  48006. if (this.particleTexture) {
  48007. serializationObject.textureName = this.particleTexture.name;
  48008. }
  48009. // Animations
  48010. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48011. // Particle system
  48012. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48013. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48014. serializationObject.minSize = this.minSize;
  48015. serializationObject.maxSize = this.maxSize;
  48016. serializationObject.minEmitPower = this.minEmitPower;
  48017. serializationObject.maxEmitPower = this.maxEmitPower;
  48018. serializationObject.minLifeTime = this.minLifeTime;
  48019. serializationObject.maxLifeTime = this.maxLifeTime;
  48020. serializationObject.emitRate = this.emitRate;
  48021. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48022. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48023. serializationObject.gravity = this.gravity.asArray();
  48024. serializationObject.direction1 = this.direction1.asArray();
  48025. serializationObject.direction2 = this.direction2.asArray();
  48026. serializationObject.color1 = this.color1.asArray();
  48027. serializationObject.color2 = this.color2.asArray();
  48028. serializationObject.colorDead = this.colorDead.asArray();
  48029. serializationObject.updateSpeed = this.updateSpeed;
  48030. serializationObject.targetStopDuration = this.targetStopDuration;
  48031. serializationObject.textureMask = this.textureMask.asArray();
  48032. serializationObject.blendMode = this.blendMode;
  48033. serializationObject.customShader = this.customShader;
  48034. serializationObject.preventAutoStart = this.preventAutoStart;
  48035. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48036. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48037. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48038. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48039. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48040. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48041. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48042. return serializationObject;
  48043. };
  48044. /**
  48045. * Parses a JSON object to create a particle system.
  48046. * @param parsedParticleSystem The JSON object to parse
  48047. * @param scene The scene to create the particle system in
  48048. * @param rootUrl The root url to use to load external dependencies like texture
  48049. * @returns the Parsed particle system
  48050. */
  48051. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48052. var name = parsedParticleSystem.name;
  48053. var custom = null;
  48054. var program = null;
  48055. if (parsedParticleSystem.customShader) {
  48056. program = parsedParticleSystem.customShader;
  48057. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48058. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48059. }
  48060. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48061. particleSystem.customShader = program;
  48062. if (parsedParticleSystem.id) {
  48063. particleSystem.id = parsedParticleSystem.id;
  48064. }
  48065. // Auto start
  48066. if (parsedParticleSystem.preventAutoStart) {
  48067. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48068. }
  48069. // Texture
  48070. if (parsedParticleSystem.textureName) {
  48071. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48072. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48073. }
  48074. // Emitter
  48075. if (parsedParticleSystem.emitterId) {
  48076. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48077. }
  48078. else {
  48079. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48080. }
  48081. // Animations
  48082. if (parsedParticleSystem.animations) {
  48083. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48084. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48085. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48086. }
  48087. }
  48088. if (parsedParticleSystem.autoAnimate) {
  48089. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48090. }
  48091. // Particle system
  48092. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48093. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48094. particleSystem.minSize = parsedParticleSystem.minSize;
  48095. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48096. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48097. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48098. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48099. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48100. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48101. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48102. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48103. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48104. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48105. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48106. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48107. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48108. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48109. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48110. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48111. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48112. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48113. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48114. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48115. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48116. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48117. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48118. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48119. if (!particleSystem.preventAutoStart) {
  48120. particleSystem.start();
  48121. }
  48122. return particleSystem;
  48123. };
  48124. /**
  48125. * Source color is added to the destination color without alpha affecting the result.
  48126. */
  48127. ParticleSystem.BLENDMODE_ONEONE = 0;
  48128. /**
  48129. * Blend current color and particle color using particle’s alpha.
  48130. */
  48131. ParticleSystem.BLENDMODE_STANDARD = 1;
  48132. return ParticleSystem;
  48133. }());
  48134. BABYLON.ParticleSystem = ParticleSystem;
  48135. })(BABYLON || (BABYLON = {}));
  48136. //# sourceMappingURL=babylon.particleSystem.js.map
  48137. var BABYLON;
  48138. (function (BABYLON) {
  48139. /**
  48140. * Particle emitter emitting particles from the inside of a box.
  48141. * It emits the particles randomly between 2 given directions.
  48142. */
  48143. var BoxParticleEmitter = /** @class */ (function () {
  48144. // to be updated like the rest of emitters when breaking changes.
  48145. // all property should be come public variables and passed through constructor.
  48146. /**
  48147. * Creates a new instance of @see BoxParticleEmitter
  48148. * @param _particleSystem the particle system associated with the emitter
  48149. */
  48150. function BoxParticleEmitter(_particleSystem) {
  48151. this._particleSystem = _particleSystem;
  48152. }
  48153. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  48154. /**
  48155. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48156. */
  48157. get: function () {
  48158. return this._particleSystem.direction1;
  48159. },
  48160. /**
  48161. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48162. */
  48163. set: function (value) {
  48164. this._particleSystem.direction1 = value;
  48165. },
  48166. enumerable: true,
  48167. configurable: true
  48168. });
  48169. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  48170. /**
  48171. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48172. */
  48173. get: function () {
  48174. return this._particleSystem.direction2;
  48175. },
  48176. /**
  48177. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48178. */
  48179. set: function (value) {
  48180. this._particleSystem.direction2 = value;
  48181. },
  48182. enumerable: true,
  48183. configurable: true
  48184. });
  48185. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  48186. /**
  48187. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48188. */
  48189. get: function () {
  48190. return this._particleSystem.minEmitBox;
  48191. },
  48192. /**
  48193. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48194. */
  48195. set: function (value) {
  48196. this._particleSystem.minEmitBox = value;
  48197. },
  48198. enumerable: true,
  48199. configurable: true
  48200. });
  48201. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  48202. /**
  48203. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48204. */
  48205. get: function () {
  48206. return this._particleSystem.maxEmitBox;
  48207. },
  48208. /**
  48209. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48210. */
  48211. set: function (value) {
  48212. this._particleSystem.maxEmitBox = value;
  48213. },
  48214. enumerable: true,
  48215. configurable: true
  48216. });
  48217. /**
  48218. * Called by the particle System when the direction is computed for the created particle.
  48219. * @param emitPower is the power of the particle (speed)
  48220. * @param worldMatrix is the world matrix of the particle system
  48221. * @param directionToUpdate is the direction vector to update with the result
  48222. * @param particle is the particle we are computed the direction for
  48223. */
  48224. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48225. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48226. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48227. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48228. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48229. };
  48230. /**
  48231. * Called by the particle System when the position is computed for the created particle.
  48232. * @param worldMatrix is the world matrix of the particle system
  48233. * @param positionToUpdate is the position vector to update with the result
  48234. * @param particle is the particle we are computed the position for
  48235. */
  48236. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48237. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  48238. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  48239. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  48240. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48241. };
  48242. return BoxParticleEmitter;
  48243. }());
  48244. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  48245. })(BABYLON || (BABYLON = {}));
  48246. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  48247. var BABYLON;
  48248. (function (BABYLON) {
  48249. /**
  48250. * Particle emitter emitting particles from the inside of a cone.
  48251. * It emits the particles alongside the cone volume from the base to the particle.
  48252. * The emission direction might be randomized.
  48253. */
  48254. var ConeParticleEmitter = /** @class */ (function () {
  48255. /**
  48256. * Creates a new instance of @see ConeParticleEmitter
  48257. * @param radius the radius of the emission cone
  48258. * @param angles the cone base angle
  48259. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48260. */
  48261. function ConeParticleEmitter(radius,
  48262. /**
  48263. * The radius of the emission cone.
  48264. */
  48265. angle,
  48266. /**
  48267. * The cone base angle.
  48268. */
  48269. directionRandomizer) {
  48270. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48271. this.angle = angle;
  48272. this.directionRandomizer = directionRandomizer;
  48273. this.radius = radius;
  48274. }
  48275. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  48276. /**
  48277. * Gets the radius of the emission cone.
  48278. */
  48279. get: function () {
  48280. return this._radius;
  48281. },
  48282. /**
  48283. * Sets the radius of the emission cone.
  48284. */
  48285. set: function (value) {
  48286. this._radius = value;
  48287. if (this.angle !== 0) {
  48288. this._height = value / Math.tan(this.angle / 2);
  48289. }
  48290. else {
  48291. this._height = 1;
  48292. }
  48293. },
  48294. enumerable: true,
  48295. configurable: true
  48296. });
  48297. /**
  48298. * Called by the particle System when the direction is computed for the created particle.
  48299. * @param emitPower is the power of the particle (speed)
  48300. * @param worldMatrix is the world matrix of the particle system
  48301. * @param directionToUpdate is the direction vector to update with the result
  48302. * @param particle is the particle we are computed the direction for
  48303. */
  48304. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48305. if (this.angle === 0) {
  48306. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  48307. }
  48308. else {
  48309. // measure the direction Vector from the emitter to the particle.
  48310. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48311. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48312. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48313. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48314. direction.x += randX;
  48315. direction.y += randY;
  48316. direction.z += randZ;
  48317. direction.normalize();
  48318. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48319. }
  48320. };
  48321. /**
  48322. * Called by the particle System when the position is computed for the created particle.
  48323. * @param worldMatrix is the world matrix of the particle system
  48324. * @param positionToUpdate is the position vector to update with the result
  48325. * @param particle is the particle we are computed the position for
  48326. */
  48327. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48328. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  48329. var h = BABYLON.Scalar.RandomRange(0, 1);
  48330. // Better distribution in a cone at normal angles.
  48331. h = 1 - h * h;
  48332. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  48333. radius = radius * h / this._height;
  48334. var randX = radius * Math.sin(s);
  48335. var randZ = radius * Math.cos(s);
  48336. var randY = h;
  48337. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48338. };
  48339. return ConeParticleEmitter;
  48340. }());
  48341. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  48342. })(BABYLON || (BABYLON = {}));
  48343. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  48344. var BABYLON;
  48345. (function (BABYLON) {
  48346. /**
  48347. * Particle emitter emitting particles from the inside of a sphere.
  48348. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  48349. */
  48350. var SphereParticleEmitter = /** @class */ (function () {
  48351. /**
  48352. * Creates a new instance of @see SphereParticleEmitter
  48353. * @param radius the radius of the emission sphere
  48354. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48355. */
  48356. function SphereParticleEmitter(
  48357. /**
  48358. * The radius of the emission sphere.
  48359. */
  48360. radius,
  48361. /**
  48362. * How much to randomize the particle direction [0-1].
  48363. */
  48364. directionRandomizer) {
  48365. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48366. this.radius = radius;
  48367. this.directionRandomizer = directionRandomizer;
  48368. }
  48369. /**
  48370. * Called by the particle System when the direction is computed for the created particle.
  48371. * @param emitPower is the power of the particle (speed)
  48372. * @param worldMatrix is the world matrix of the particle system
  48373. * @param directionToUpdate is the direction vector to update with the result
  48374. * @param particle is the particle we are computed the direction for
  48375. */
  48376. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48377. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48378. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48379. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48380. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48381. direction.x += randX;
  48382. direction.y += randY;
  48383. direction.z += randZ;
  48384. direction.normalize();
  48385. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48386. };
  48387. /**
  48388. * Called by the particle System when the position is computed for the created particle.
  48389. * @param worldMatrix is the world matrix of the particle system
  48390. * @param positionToUpdate is the position vector to update with the result
  48391. * @param particle is the particle we are computed the position for
  48392. */
  48393. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48394. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48395. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48396. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48397. var randY = this.radius * Math.cos(theta);
  48398. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48399. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48400. };
  48401. return SphereParticleEmitter;
  48402. }());
  48403. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48404. /**
  48405. * Particle emitter emitting particles from the inside of a sphere.
  48406. * It emits the particles randomly between two vectors.
  48407. */
  48408. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48409. __extends(SphereDirectedParticleEmitter, _super);
  48410. /**
  48411. * Creates a new instance of @see SphereDirectedParticleEmitter
  48412. * @param radius the radius of the emission sphere
  48413. * @param direction1 the min limit of the emission direction
  48414. * @param direction2 the max limit of the emission direction
  48415. */
  48416. function SphereDirectedParticleEmitter(radius,
  48417. /**
  48418. * The min limit of the emission direction.
  48419. */
  48420. direction1,
  48421. /**
  48422. * The max limit of the emission direction.
  48423. */
  48424. direction2) {
  48425. var _this = _super.call(this, radius) || this;
  48426. _this.direction1 = direction1;
  48427. _this.direction2 = direction2;
  48428. return _this;
  48429. }
  48430. /**
  48431. * Called by the particle System when the direction is computed for the created particle.
  48432. * @param emitPower is the power of the particle (speed)
  48433. * @param worldMatrix is the world matrix of the particle system
  48434. * @param directionToUpdate is the direction vector to update with the result
  48435. * @param particle is the particle we are computed the direction for
  48436. */
  48437. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48438. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48439. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48440. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48441. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48442. };
  48443. return SphereDirectedParticleEmitter;
  48444. }(SphereParticleEmitter));
  48445. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48446. })(BABYLON || (BABYLON = {}));
  48447. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48448. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  48449. var BABYLON;
  48450. (function (BABYLON) {
  48451. /**
  48452. * Represents one particle of a solid particle system.
  48453. * @see SolidParticleSystem
  48454. */
  48455. var SolidParticle = /** @class */ (function () {
  48456. /**
  48457. * Creates a Solid Particle object.
  48458. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48459. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48460. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48461. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  48462. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  48463. * @param shapeId (integer) is the model shape identifier in the SPS.
  48464. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48465. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  48466. */
  48467. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48468. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  48469. /**
  48470. * particle global index
  48471. */
  48472. this.idx = 0;
  48473. /**
  48474. * The color of the particle
  48475. */
  48476. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48477. /**
  48478. * The world space position of the particle.
  48479. */
  48480. this.position = BABYLON.Vector3.Zero();
  48481. /**
  48482. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  48483. */
  48484. this.rotation = BABYLON.Vector3.Zero();
  48485. /**
  48486. * The scaling of the particle.
  48487. */
  48488. this.scaling = BABYLON.Vector3.One();
  48489. /**
  48490. * The uvs of the particle.
  48491. */
  48492. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  48493. /**
  48494. * The current speed of the particle.
  48495. */
  48496. this.velocity = BABYLON.Vector3.Zero();
  48497. /**
  48498. * The pivot point in the particle local space.
  48499. */
  48500. this.pivot = BABYLON.Vector3.Zero();
  48501. /**
  48502. * Is the particle active or not ?
  48503. */
  48504. this.alive = true;
  48505. /**
  48506. * Is the particle visible or not ?
  48507. */
  48508. this.isVisible = true;
  48509. /**
  48510. * Index of this particle in the global "positions" array (Internal use)
  48511. */
  48512. this._pos = 0;
  48513. /**
  48514. * Index of this particle in the global "indices" array (Internal use)
  48515. */
  48516. this._ind = 0;
  48517. /**
  48518. * ModelShape id of this particle
  48519. */
  48520. this.shapeId = 0;
  48521. /**
  48522. * Index of the particle in its shape id (Internal use)
  48523. */
  48524. this.idxInShape = 0;
  48525. /**
  48526. * Still set as invisible in order to skip useless computations (Internal use)
  48527. */
  48528. this._stillInvisible = false;
  48529. this.idx = particleIndex;
  48530. this._pos = positionIndex;
  48531. this._ind = indiceIndex;
  48532. this._model = model;
  48533. this.shapeId = shapeId;
  48534. this.idxInShape = idxInShape;
  48535. this._sps = sps;
  48536. if (modelBoundingInfo) {
  48537. this._modelBoundingInfo = modelBoundingInfo;
  48538. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48539. }
  48540. }
  48541. Object.defineProperty(SolidParticle.prototype, "scale", {
  48542. /**
  48543. * Legacy support, changed scale to scaling
  48544. */
  48545. get: function () {
  48546. return this.scaling;
  48547. },
  48548. /**
  48549. * Legacy support, changed scale to scaling
  48550. */
  48551. set: function (scale) {
  48552. this.scaling = scale;
  48553. },
  48554. enumerable: true,
  48555. configurable: true
  48556. });
  48557. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48558. /**
  48559. * Legacy support, changed quaternion to rotationQuaternion
  48560. */
  48561. get: function () {
  48562. return this.rotationQuaternion;
  48563. },
  48564. /**
  48565. * Legacy support, changed quaternion to rotationQuaternion
  48566. */
  48567. set: function (q) {
  48568. this.rotationQuaternion = q;
  48569. },
  48570. enumerable: true,
  48571. configurable: true
  48572. });
  48573. /**
  48574. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48575. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48576. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  48577. * @returns true if it intersects
  48578. */
  48579. SolidParticle.prototype.intersectsMesh = function (target) {
  48580. if (!this._boundingInfo || !target._boundingInfo) {
  48581. return false;
  48582. }
  48583. if (this._sps._bSphereOnly) {
  48584. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48585. }
  48586. return this._boundingInfo.intersects(target._boundingInfo, false);
  48587. };
  48588. return SolidParticle;
  48589. }());
  48590. BABYLON.SolidParticle = SolidParticle;
  48591. /**
  48592. * Represents the shape of the model used by one particle of a solid particle system.
  48593. * SPS internal tool, don't use it manually.
  48594. * @see SolidParticleSystem
  48595. */
  48596. var ModelShape = /** @class */ (function () {
  48597. /**
  48598. * 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.
  48599. * SPS internal tool, don't use it manually.
  48600. * @ignore
  48601. */
  48602. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  48603. /**
  48604. * length of the shape in the model indices array (internal use)
  48605. */
  48606. this._indicesLength = 0;
  48607. this.shapeID = id;
  48608. this._shape = shape;
  48609. this._indicesLength = indicesLength;
  48610. this._shapeUV = shapeUV;
  48611. this._positionFunction = posFunction;
  48612. this._vertexFunction = vtxFunction;
  48613. }
  48614. return ModelShape;
  48615. }());
  48616. BABYLON.ModelShape = ModelShape;
  48617. /**
  48618. * Represents a Depth Sorted Particle in the solid particle system.
  48619. * @see SolidParticleSystem
  48620. */
  48621. var DepthSortedParticle = /** @class */ (function () {
  48622. function DepthSortedParticle() {
  48623. /**
  48624. * Index of the particle in the "indices" array
  48625. */
  48626. this.ind = 0;
  48627. /**
  48628. * Length of the particle shape in the "indices" array
  48629. */
  48630. this.indicesLength = 0;
  48631. /**
  48632. * Squared distance from the particle to the camera
  48633. */
  48634. this.sqDistance = 0.0;
  48635. }
  48636. return DepthSortedParticle;
  48637. }());
  48638. BABYLON.DepthSortedParticle = DepthSortedParticle;
  48639. })(BABYLON || (BABYLON = {}));
  48640. //# sourceMappingURL=babylon.solidParticle.js.map
  48641. var BABYLON;
  48642. (function (BABYLON) {
  48643. /**
  48644. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  48645. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  48646. * The SPS is also a particle system. It provides some methods to manage the particles.
  48647. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  48648. *
  48649. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48650. */
  48651. var SolidParticleSystem = /** @class */ (function () {
  48652. /**
  48653. * Creates a SPS (Solid Particle System) object.
  48654. * @param name (String) is the SPS name, this will be the underlying mesh name.
  48655. * @param scene (Scene) is the scene in which the SPS is added.
  48656. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  48657. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  48658. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  48659. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  48660. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48661. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48662. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48663. */
  48664. function SolidParticleSystem(name, scene, options) {
  48665. /**
  48666. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48667. * Example : var p = SPS.particles[i];
  48668. */
  48669. this.particles = new Array();
  48670. /**
  48671. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48672. */
  48673. this.nbParticles = 0;
  48674. /**
  48675. * If the particles must ever face the camera (default false). Useful for planar particles.
  48676. */
  48677. this.billboard = false;
  48678. /**
  48679. * Recompute normals when adding a shape
  48680. */
  48681. this.recomputeNormals = true;
  48682. /**
  48683. * This a counter ofr your own usage. It's not set by any SPS functions.
  48684. */
  48685. this.counter = 0;
  48686. /**
  48687. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48688. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48689. */
  48690. this.vars = {};
  48691. /**
  48692. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  48693. */
  48694. this._bSphereOnly = false;
  48695. /**
  48696. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  48697. */
  48698. this._bSphereRadiusFactor = 1.0;
  48699. this._positions = new Array();
  48700. this._indices = new Array();
  48701. this._normals = new Array();
  48702. this._colors = new Array();
  48703. this._uvs = new Array();
  48704. this._index = 0; // indices index
  48705. this._updatable = true;
  48706. this._pickable = false;
  48707. this._isVisibilityBoxLocked = false;
  48708. this._alwaysVisible = false;
  48709. this._depthSort = false;
  48710. this._shapeCounter = 0;
  48711. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  48712. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48713. this._computeParticleColor = true;
  48714. this._computeParticleTexture = true;
  48715. this._computeParticleRotation = true;
  48716. this._computeParticleVertex = false;
  48717. this._computeBoundingBox = false;
  48718. this._depthSortParticles = true;
  48719. this._cam_axisZ = BABYLON.Vector3.Zero();
  48720. this._cam_axisY = BABYLON.Vector3.Zero();
  48721. this._cam_axisX = BABYLON.Vector3.Zero();
  48722. this._axisZ = BABYLON.Axis.Z;
  48723. this._camDir = BABYLON.Vector3.Zero();
  48724. this._camInvertedPosition = BABYLON.Vector3.Zero();
  48725. this._rotMatrix = new BABYLON.Matrix();
  48726. this._invertMatrix = new BABYLON.Matrix();
  48727. this._rotated = BABYLON.Vector3.Zero();
  48728. this._quaternion = new BABYLON.Quaternion();
  48729. this._vertex = BABYLON.Vector3.Zero();
  48730. this._normal = BABYLON.Vector3.Zero();
  48731. this._yaw = 0.0;
  48732. this._pitch = 0.0;
  48733. this._roll = 0.0;
  48734. this._halfroll = 0.0;
  48735. this._halfpitch = 0.0;
  48736. this._halfyaw = 0.0;
  48737. this._sinRoll = 0.0;
  48738. this._cosRoll = 0.0;
  48739. this._sinPitch = 0.0;
  48740. this._cosPitch = 0.0;
  48741. this._sinYaw = 0.0;
  48742. this._cosYaw = 0.0;
  48743. this._mustUnrotateFixedNormals = false;
  48744. this._minimum = BABYLON.Tmp.Vector3[0];
  48745. this._maximum = BABYLON.Tmp.Vector3[1];
  48746. this._minBbox = BABYLON.Tmp.Vector3[4];
  48747. this._maxBbox = BABYLON.Tmp.Vector3[5];
  48748. this._particlesIntersect = false;
  48749. this._depthSortFunction = function (p1, p2) {
  48750. return (p2.sqDistance - p1.sqDistance);
  48751. };
  48752. this._needs32Bits = false;
  48753. this.name = name;
  48754. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48755. this._camera = scene.activeCamera;
  48756. this._pickable = options ? options.isPickable : false;
  48757. this._depthSort = options ? options.enableDepthSort : false;
  48758. this._particlesIntersect = options ? options.particleIntersection : false;
  48759. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  48760. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  48761. if (options && options.updatable) {
  48762. this._updatable = options.updatable;
  48763. }
  48764. else {
  48765. this._updatable = true;
  48766. }
  48767. if (this._pickable) {
  48768. this.pickedParticles = [];
  48769. }
  48770. if (this._depthSort) {
  48771. this.depthSortedParticles = [];
  48772. }
  48773. }
  48774. /**
  48775. * Builds the SPS underlying mesh. Returns a standard Mesh.
  48776. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  48777. * @returns the created mesh
  48778. */
  48779. SolidParticleSystem.prototype.buildMesh = function () {
  48780. if (this.nbParticles === 0) {
  48781. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  48782. this.addShape(triangle, 1);
  48783. triangle.dispose();
  48784. }
  48785. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  48786. this._positions32 = new Float32Array(this._positions);
  48787. this._uvs32 = new Float32Array(this._uvs);
  48788. this._colors32 = new Float32Array(this._colors);
  48789. if (this.recomputeNormals) {
  48790. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  48791. }
  48792. this._normals32 = new Float32Array(this._normals);
  48793. this._fixedNormal32 = new Float32Array(this._normals);
  48794. if (this._mustUnrotateFixedNormals) {
  48795. this._unrotateFixedNormals();
  48796. }
  48797. var vertexData = new BABYLON.VertexData();
  48798. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  48799. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  48800. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  48801. if (this._uvs32) {
  48802. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  48803. ;
  48804. }
  48805. if (this._colors32) {
  48806. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  48807. }
  48808. var mesh = new BABYLON.Mesh(this.name, this._scene);
  48809. vertexData.applyToMesh(mesh, this._updatable);
  48810. this.mesh = mesh;
  48811. this.mesh.isPickable = this._pickable;
  48812. // free memory
  48813. if (!this._depthSort) {
  48814. this._indices = null;
  48815. }
  48816. this._positions = null;
  48817. this._normals = null;
  48818. this._uvs = null;
  48819. this._colors = null;
  48820. if (!this._updatable) {
  48821. this.particles.length = 0;
  48822. }
  48823. return mesh;
  48824. };
  48825. /**
  48826. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  48827. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  48828. * Thus the particles generated from `digest()` have their property `position` set yet.
  48829. * @param mesh ( Mesh ) is the mesh to be digested
  48830. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  48831. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  48832. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  48833. * @returns the current SPS
  48834. */
  48835. SolidParticleSystem.prototype.digest = function (mesh, options) {
  48836. var size = (options && options.facetNb) || 1;
  48837. var number = (options && options.number) || 0;
  48838. var delta = (options && options.delta) || 0;
  48839. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48840. var meshInd = mesh.getIndices();
  48841. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48842. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48843. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48844. var f = 0; // facet counter
  48845. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  48846. // compute size from number
  48847. if (number) {
  48848. number = (number > totalFacets) ? totalFacets : number;
  48849. size = Math.round(totalFacets / number);
  48850. delta = 0;
  48851. }
  48852. else {
  48853. size = (size > totalFacets) ? totalFacets : size;
  48854. }
  48855. var facetPos = []; // submesh positions
  48856. var facetInd = []; // submesh indices
  48857. var facetUV = []; // submesh UV
  48858. var facetCol = []; // submesh colors
  48859. var barycenter = BABYLON.Tmp.Vector3[0];
  48860. var sizeO = size;
  48861. while (f < totalFacets) {
  48862. size = sizeO + Math.floor((1 + delta) * Math.random());
  48863. if (f > totalFacets - size) {
  48864. size = totalFacets - f;
  48865. }
  48866. // reset temp arrays
  48867. facetPos.length = 0;
  48868. facetInd.length = 0;
  48869. facetUV.length = 0;
  48870. facetCol.length = 0;
  48871. // iterate over "size" facets
  48872. var fi = 0;
  48873. for (var j = f * 3; j < (f + size) * 3; j++) {
  48874. facetInd.push(fi);
  48875. var i = meshInd[j];
  48876. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  48877. if (meshUV) {
  48878. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  48879. }
  48880. if (meshCol) {
  48881. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  48882. }
  48883. fi++;
  48884. }
  48885. // create a model shape for each single particle
  48886. var idx = this.nbParticles;
  48887. var shape = this._posToShape(facetPos);
  48888. var shapeUV = this._uvsToShapeUV(facetUV);
  48889. // compute the barycenter of the shape
  48890. var v;
  48891. for (v = 0; v < shape.length; v++) {
  48892. barycenter.addInPlace(shape[v]);
  48893. }
  48894. barycenter.scaleInPlace(1 / shape.length);
  48895. // shift the shape from its barycenter to the origin
  48896. for (v = 0; v < shape.length; v++) {
  48897. shape[v].subtractInPlace(barycenter);
  48898. }
  48899. var bInfo;
  48900. if (this._particlesIntersect) {
  48901. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  48902. }
  48903. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  48904. // add the particle in the SPS
  48905. var currentPos = this._positions.length;
  48906. var currentInd = this._indices.length;
  48907. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  48908. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  48909. // initialize the particle position
  48910. this.particles[this.nbParticles].position.addInPlace(barycenter);
  48911. this._index += shape.length;
  48912. idx++;
  48913. this.nbParticles++;
  48914. this._shapeCounter++;
  48915. f += size;
  48916. }
  48917. return this;
  48918. };
  48919. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  48920. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  48921. var index = 0;
  48922. var idx = 0;
  48923. for (var p = 0; p < this.particles.length; p++) {
  48924. this._particle = this.particles[p];
  48925. this._shape = this._particle._model._shape;
  48926. if (this._particle.rotationQuaternion) {
  48927. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48928. }
  48929. else {
  48930. this._yaw = this._particle.rotation.y;
  48931. this._pitch = this._particle.rotation.x;
  48932. this._roll = this._particle.rotation.z;
  48933. this._quaternionRotationYPR();
  48934. }
  48935. this._quaternionToRotationMatrix();
  48936. this._rotMatrix.invertToRef(this._invertMatrix);
  48937. for (var pt = 0; pt < this._shape.length; pt++) {
  48938. idx = index + pt * 3;
  48939. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  48940. this._fixedNormal32[idx] = this._normal.x;
  48941. this._fixedNormal32[idx + 1] = this._normal.y;
  48942. this._fixedNormal32[idx + 2] = this._normal.z;
  48943. }
  48944. index = idx + 3;
  48945. }
  48946. };
  48947. //reset copy
  48948. SolidParticleSystem.prototype._resetCopy = function () {
  48949. this._copy.position.x = 0;
  48950. this._copy.position.y = 0;
  48951. this._copy.position.z = 0;
  48952. this._copy.rotation.x = 0;
  48953. this._copy.rotation.y = 0;
  48954. this._copy.rotation.z = 0;
  48955. this._copy.rotationQuaternion = null;
  48956. this._copy.scaling.x = 1.0;
  48957. this._copy.scaling.y = 1.0;
  48958. this._copy.scaling.z = 1.0;
  48959. this._copy.uvs.x = 0;
  48960. this._copy.uvs.y = 0;
  48961. this._copy.uvs.z = 1.0;
  48962. this._copy.uvs.w = 1.0;
  48963. this._copy.color = null;
  48964. };
  48965. // _meshBuilder : inserts the shape model in the global SPS mesh
  48966. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  48967. var i;
  48968. var u = 0;
  48969. var c = 0;
  48970. var n = 0;
  48971. this._resetCopy();
  48972. if (options && options.positionFunction) {
  48973. options.positionFunction(this._copy, idx, idxInShape);
  48974. this._mustUnrotateFixedNormals = true;
  48975. }
  48976. if (this._copy.rotationQuaternion) {
  48977. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48978. }
  48979. else {
  48980. this._yaw = this._copy.rotation.y;
  48981. this._pitch = this._copy.rotation.x;
  48982. this._roll = this._copy.rotation.z;
  48983. this._quaternionRotationYPR();
  48984. }
  48985. this._quaternionToRotationMatrix();
  48986. for (i = 0; i < shape.length; i++) {
  48987. this._vertex.x = shape[i].x;
  48988. this._vertex.y = shape[i].y;
  48989. this._vertex.z = shape[i].z;
  48990. if (options && options.vertexFunction) {
  48991. options.vertexFunction(this._copy, this._vertex, i);
  48992. }
  48993. this._vertex.x *= this._copy.scaling.x;
  48994. this._vertex.y *= this._copy.scaling.y;
  48995. this._vertex.z *= this._copy.scaling.z;
  48996. this._vertex.x += this._copy.pivot.x;
  48997. this._vertex.y += this._copy.pivot.y;
  48998. this._vertex.z += this._copy.pivot.z;
  48999. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49000. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49001. if (meshUV) {
  49002. 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);
  49003. u += 2;
  49004. }
  49005. if (this._copy.color) {
  49006. this._color = this._copy.color;
  49007. }
  49008. else if (meshCol && meshCol[c] !== undefined) {
  49009. this._color.r = meshCol[c];
  49010. this._color.g = meshCol[c + 1];
  49011. this._color.b = meshCol[c + 2];
  49012. this._color.a = meshCol[c + 3];
  49013. }
  49014. else {
  49015. this._color.r = 1.0;
  49016. this._color.g = 1.0;
  49017. this._color.b = 1.0;
  49018. this._color.a = 1.0;
  49019. }
  49020. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49021. c += 4;
  49022. if (!this.recomputeNormals && meshNor) {
  49023. this._normal.x = meshNor[n];
  49024. this._normal.y = meshNor[n + 1];
  49025. this._normal.z = meshNor[n + 2];
  49026. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49027. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49028. n += 3;
  49029. }
  49030. }
  49031. for (i = 0; i < meshInd.length; i++) {
  49032. var current_ind = p + meshInd[i];
  49033. indices.push(current_ind);
  49034. if (current_ind > 65535) {
  49035. this._needs32Bits = true;
  49036. }
  49037. }
  49038. if (this._pickable) {
  49039. var nbfaces = meshInd.length / 3;
  49040. for (i = 0; i < nbfaces; i++) {
  49041. this.pickedParticles.push({ idx: idx, faceId: i });
  49042. }
  49043. }
  49044. if (this._depthSort) {
  49045. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49046. }
  49047. return this._copy;
  49048. };
  49049. // returns a shape array from positions array
  49050. SolidParticleSystem.prototype._posToShape = function (positions) {
  49051. var shape = [];
  49052. for (var i = 0; i < positions.length; i += 3) {
  49053. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49054. }
  49055. return shape;
  49056. };
  49057. // returns a shapeUV array from a Vector4 uvs
  49058. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49059. var shapeUV = [];
  49060. if (uvs) {
  49061. for (var i = 0; i < uvs.length; i++)
  49062. shapeUV.push(uvs[i]);
  49063. }
  49064. return shapeUV;
  49065. };
  49066. // adds a new particle object in the particles array
  49067. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49068. if (bInfo === void 0) { bInfo = null; }
  49069. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49070. this.particles.push(sp);
  49071. return sp;
  49072. };
  49073. /**
  49074. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49075. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49076. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49077. * @param nb (positive integer) the number of particles to be created from this model
  49078. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  49079. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  49080. * @returns the number of shapes in the system
  49081. */
  49082. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49083. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49084. var meshInd = mesh.getIndices();
  49085. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49086. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49087. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49088. var bbInfo;
  49089. if (this._particlesIntersect) {
  49090. bbInfo = mesh.getBoundingInfo();
  49091. }
  49092. var shape = this._posToShape(meshPos);
  49093. var shapeUV = this._uvsToShapeUV(meshUV);
  49094. var posfunc = options ? options.positionFunction : null;
  49095. var vtxfunc = options ? options.vertexFunction : null;
  49096. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  49097. // particles
  49098. var sp;
  49099. var currentCopy;
  49100. var idx = this.nbParticles;
  49101. for (var i = 0; i < nb; i++) {
  49102. var currentPos = this._positions.length;
  49103. var currentInd = this._indices.length;
  49104. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49105. if (this._updatable) {
  49106. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  49107. sp.position.copyFrom(currentCopy.position);
  49108. sp.rotation.copyFrom(currentCopy.rotation);
  49109. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  49110. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  49111. }
  49112. if (currentCopy.color && sp.color) {
  49113. sp.color.copyFrom(currentCopy.color);
  49114. }
  49115. sp.scaling.copyFrom(currentCopy.scaling);
  49116. sp.uvs.copyFrom(currentCopy.uvs);
  49117. }
  49118. this._index += shape.length;
  49119. idx++;
  49120. }
  49121. this.nbParticles += nb;
  49122. this._shapeCounter++;
  49123. return this._shapeCounter - 1;
  49124. };
  49125. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49126. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49127. this._resetCopy();
  49128. if (particle._model._positionFunction) {
  49129. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49130. }
  49131. if (this._copy.rotationQuaternion) {
  49132. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49133. }
  49134. else {
  49135. this._yaw = this._copy.rotation.y;
  49136. this._pitch = this._copy.rotation.x;
  49137. this._roll = this._copy.rotation.z;
  49138. this._quaternionRotationYPR();
  49139. }
  49140. this._quaternionToRotationMatrix();
  49141. this._shape = particle._model._shape;
  49142. for (var pt = 0; pt < this._shape.length; pt++) {
  49143. this._vertex.x = this._shape[pt].x;
  49144. this._vertex.y = this._shape[pt].y;
  49145. this._vertex.z = this._shape[pt].z;
  49146. if (particle._model._vertexFunction) {
  49147. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49148. }
  49149. this._vertex.x *= this._copy.scaling.x;
  49150. this._vertex.y *= this._copy.scaling.y;
  49151. this._vertex.z *= this._copy.scaling.z;
  49152. this._vertex.x += this._copy.pivot.x;
  49153. this._vertex.y += this._copy.pivot.y;
  49154. this._vertex.z += this._copy.pivot.z;
  49155. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49156. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49157. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49158. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49159. }
  49160. particle.position.x = 0.0;
  49161. particle.position.y = 0.0;
  49162. particle.position.z = 0.0;
  49163. particle.rotation.x = 0.0;
  49164. particle.rotation.y = 0.0;
  49165. particle.rotation.z = 0.0;
  49166. particle.rotationQuaternion = null;
  49167. particle.scaling.x = 1.0;
  49168. particle.scaling.y = 1.0;
  49169. particle.scaling.z = 1.0;
  49170. };
  49171. /**
  49172. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49173. * @returns the SPS.
  49174. */
  49175. SolidParticleSystem.prototype.rebuildMesh = function () {
  49176. for (var p = 0; p < this.particles.length; p++) {
  49177. this._rebuildParticle(this.particles[p]);
  49178. }
  49179. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49180. return this;
  49181. };
  49182. /**
  49183. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49184. * This method calls `updateParticle()` for each particle of the SPS.
  49185. * For an animated SPS, it is usually called within the render loop.
  49186. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49187. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49188. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49189. * @returns the SPS.
  49190. */
  49191. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49192. if (start === void 0) { start = 0; }
  49193. if (end === void 0) { end = this.nbParticles - 1; }
  49194. if (update === void 0) { update = true; }
  49195. if (!this._updatable) {
  49196. return this;
  49197. }
  49198. // custom beforeUpdate
  49199. this.beforeUpdateParticles(start, end, update);
  49200. this._cam_axisX.x = 1.0;
  49201. this._cam_axisX.y = 0.0;
  49202. this._cam_axisX.z = 0.0;
  49203. this._cam_axisY.x = 0.0;
  49204. this._cam_axisY.y = 1.0;
  49205. this._cam_axisY.z = 0.0;
  49206. this._cam_axisZ.x = 0.0;
  49207. this._cam_axisZ.y = 0.0;
  49208. this._cam_axisZ.z = 1.0;
  49209. // cases when the World Matrix is to be computed first
  49210. if (this.billboard || this._depthSort) {
  49211. this.mesh.computeWorldMatrix(true);
  49212. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49213. }
  49214. // if the particles will always face the camera
  49215. if (this.billboard) {
  49216. // compute the camera position and un-rotate it by the current mesh rotation
  49217. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49218. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49219. this._cam_axisZ.normalize();
  49220. // same for camera up vector extracted from the cam view matrix
  49221. var view = this._camera.getViewMatrix(true);
  49222. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49223. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49224. this._cam_axisY.normalize();
  49225. this._cam_axisX.normalize();
  49226. }
  49227. // if depthSort, compute the camera global position in the mesh local system
  49228. if (this._depthSort) {
  49229. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49230. }
  49231. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49232. var idx = 0; // current position index in the global array positions32
  49233. var index = 0; // position start index in the global array positions32 of the current particle
  49234. var colidx = 0; // current color index in the global array colors32
  49235. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49236. var uvidx = 0; // current uv index in the global array uvs32
  49237. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49238. var pt = 0; // current index in the particle model shape
  49239. if (this.mesh.isFacetDataEnabled) {
  49240. this._computeBoundingBox = true;
  49241. }
  49242. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49243. if (this._computeBoundingBox) {
  49244. if (start == 0 && end == this.nbParticles - 1) {
  49245. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49246. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49247. }
  49248. else {
  49249. if (this.mesh._boundingInfo) {
  49250. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49251. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49252. }
  49253. }
  49254. }
  49255. // particle loop
  49256. index = this.particles[start]._pos;
  49257. var vpos = (index / 3) | 0;
  49258. colorIndex = vpos * 4;
  49259. uvIndex = vpos * 2;
  49260. for (var p = start; p <= end; p++) {
  49261. this._particle = this.particles[p];
  49262. this._shape = this._particle._model._shape;
  49263. this._shapeUV = this._particle._model._shapeUV;
  49264. // call to custom user function to update the particle properties
  49265. this.updateParticle(this._particle);
  49266. // camera-particle distance for depth sorting
  49267. if (this._depthSort && this._depthSortParticles) {
  49268. var dsp = this.depthSortedParticles[p];
  49269. dsp.ind = this._particle._ind;
  49270. dsp.indicesLength = this._particle._model._indicesLength;
  49271. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49272. }
  49273. // skip the computations for inactive or already invisible particles
  49274. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49275. // increment indexes for the next particle
  49276. pt = this._shape.length;
  49277. index += pt * 3;
  49278. colorIndex += pt * 4;
  49279. uvIndex += pt * 2;
  49280. continue;
  49281. }
  49282. if (this._particle.isVisible) {
  49283. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49284. // particle rotation matrix
  49285. if (this.billboard) {
  49286. this._particle.rotation.x = 0.0;
  49287. this._particle.rotation.y = 0.0;
  49288. }
  49289. if (this._computeParticleRotation || this.billboard) {
  49290. if (this._particle.rotationQuaternion) {
  49291. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49292. }
  49293. else {
  49294. this._yaw = this._particle.rotation.y;
  49295. this._pitch = this._particle.rotation.x;
  49296. this._roll = this._particle.rotation.z;
  49297. this._quaternionRotationYPR();
  49298. }
  49299. this._quaternionToRotationMatrix();
  49300. }
  49301. // particle vertex loop
  49302. for (pt = 0; pt < this._shape.length; pt++) {
  49303. idx = index + pt * 3;
  49304. colidx = colorIndex + pt * 4;
  49305. uvidx = uvIndex + pt * 2;
  49306. this._vertex.x = this._shape[pt].x;
  49307. this._vertex.y = this._shape[pt].y;
  49308. this._vertex.z = this._shape[pt].z;
  49309. if (this._computeParticleVertex) {
  49310. this.updateParticleVertex(this._particle, this._vertex, pt);
  49311. }
  49312. // positions
  49313. this._vertex.x *= this._particle.scaling.x;
  49314. this._vertex.y *= this._particle.scaling.y;
  49315. this._vertex.z *= this._particle.scaling.z;
  49316. this._vertex.x += this._particle.pivot.x;
  49317. this._vertex.y += this._particle.pivot.y;
  49318. this._vertex.z += this._particle.pivot.z;
  49319. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49320. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49321. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49322. 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;
  49323. 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;
  49324. 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;
  49325. if (this._computeBoundingBox) {
  49326. if (this._positions32[idx] < this._minimum.x) {
  49327. this._minimum.x = this._positions32[idx];
  49328. }
  49329. if (this._positions32[idx] > this._maximum.x) {
  49330. this._maximum.x = this._positions32[idx];
  49331. }
  49332. if (this._positions32[idx + 1] < this._minimum.y) {
  49333. this._minimum.y = this._positions32[idx + 1];
  49334. }
  49335. if (this._positions32[idx + 1] > this._maximum.y) {
  49336. this._maximum.y = this._positions32[idx + 1];
  49337. }
  49338. if (this._positions32[idx + 2] < this._minimum.z) {
  49339. this._minimum.z = this._positions32[idx + 2];
  49340. }
  49341. if (this._positions32[idx + 2] > this._maximum.z) {
  49342. this._maximum.z = this._positions32[idx + 2];
  49343. }
  49344. }
  49345. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49346. if (!this._computeParticleVertex) {
  49347. this._normal.x = this._fixedNormal32[idx];
  49348. this._normal.y = this._fixedNormal32[idx + 1];
  49349. this._normal.z = this._fixedNormal32[idx + 2];
  49350. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49351. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49352. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49353. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49354. 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;
  49355. 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;
  49356. }
  49357. if (this._computeParticleColor && this._particle.color) {
  49358. this._colors32[colidx] = this._particle.color.r;
  49359. this._colors32[colidx + 1] = this._particle.color.g;
  49360. this._colors32[colidx + 2] = this._particle.color.b;
  49361. this._colors32[colidx + 3] = this._particle.color.a;
  49362. }
  49363. if (this._computeParticleTexture) {
  49364. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49365. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49366. }
  49367. }
  49368. }
  49369. else {
  49370. this._particle._stillInvisible = true; // mark the particle as invisible
  49371. for (pt = 0; pt < this._shape.length; pt++) {
  49372. idx = index + pt * 3;
  49373. colidx = colorIndex + pt * 4;
  49374. uvidx = uvIndex + pt * 2;
  49375. this._positions32[idx] = 0.0;
  49376. this._positions32[idx + 1] = 0.0;
  49377. this._positions32[idx + 2] = 0.0;
  49378. this._normals32[idx] = 0.0;
  49379. this._normals32[idx + 1] = 0.0;
  49380. this._normals32[idx + 2] = 0.0;
  49381. if (this._computeParticleColor && this._particle.color) {
  49382. this._colors32[colidx] = this._particle.color.r;
  49383. this._colors32[colidx + 1] = this._particle.color.g;
  49384. this._colors32[colidx + 2] = this._particle.color.b;
  49385. this._colors32[colidx + 3] = this._particle.color.a;
  49386. }
  49387. if (this._computeParticleTexture) {
  49388. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49389. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49390. }
  49391. }
  49392. }
  49393. // if the particle intersections must be computed : update the bbInfo
  49394. if (this._particlesIntersect) {
  49395. var bInfo = this._particle._boundingInfo;
  49396. var bBox = bInfo.boundingBox;
  49397. var bSphere = bInfo.boundingSphere;
  49398. if (!this._bSphereOnly) {
  49399. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49400. for (var b = 0; b < bBox.vectors.length; b++) {
  49401. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49402. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49403. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49404. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49405. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49406. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49407. 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;
  49408. 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;
  49409. 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;
  49410. }
  49411. bBox._update(this.mesh._worldMatrix);
  49412. }
  49413. // place and scale the particle bouding sphere in the SPS local system, then update it
  49414. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49415. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49416. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49417. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49418. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49419. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49420. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49421. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49422. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49423. 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));
  49424. bSphere._update(this.mesh._worldMatrix);
  49425. }
  49426. // increment indexes for the next particle
  49427. index = idx + 3;
  49428. colorIndex = colidx + 4;
  49429. uvIndex = uvidx + 2;
  49430. }
  49431. // if the VBO must be updated
  49432. if (update) {
  49433. if (this._computeParticleColor) {
  49434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49435. }
  49436. if (this._computeParticleTexture) {
  49437. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49438. }
  49439. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49440. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  49441. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  49442. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49443. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  49444. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  49445. for (var i = 0; i < this._normals32.length; i++) {
  49446. this._fixedNormal32[i] = this._normals32[i];
  49447. }
  49448. }
  49449. if (!this.mesh.areNormalsFrozen) {
  49450. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49451. }
  49452. }
  49453. if (this._depthSort && this._depthSortParticles) {
  49454. this.depthSortedParticles.sort(this._depthSortFunction);
  49455. var dspl = this.depthSortedParticles.length;
  49456. var sorted = 0;
  49457. var lind = 0;
  49458. var sind = 0;
  49459. var sid = 0;
  49460. for (sorted = 0; sorted < dspl; sorted++) {
  49461. lind = this.depthSortedParticles[sorted].indicesLength;
  49462. sind = this.depthSortedParticles[sorted].ind;
  49463. for (var i = 0; i < lind; i++) {
  49464. this._indices32[sid] = this._indices[sind + i];
  49465. sid++;
  49466. }
  49467. }
  49468. this.mesh.updateIndices(this._indices32);
  49469. }
  49470. }
  49471. if (this._computeBoundingBox) {
  49472. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49473. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49474. }
  49475. this.afterUpdateParticles(start, end, update);
  49476. return this;
  49477. };
  49478. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49479. this._halfroll = this._roll * 0.5;
  49480. this._halfpitch = this._pitch * 0.5;
  49481. this._halfyaw = this._yaw * 0.5;
  49482. this._sinRoll = Math.sin(this._halfroll);
  49483. this._cosRoll = Math.cos(this._halfroll);
  49484. this._sinPitch = Math.sin(this._halfpitch);
  49485. this._cosPitch = Math.cos(this._halfpitch);
  49486. this._sinYaw = Math.sin(this._halfyaw);
  49487. this._cosYaw = Math.cos(this._halfyaw);
  49488. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  49489. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  49490. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  49491. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  49492. };
  49493. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49494. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49495. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49496. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49497. this._rotMatrix.m[3] = 0;
  49498. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49499. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49500. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49501. this._rotMatrix.m[7] = 0;
  49502. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49503. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49504. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49505. this._rotMatrix.m[11] = 0;
  49506. this._rotMatrix.m[12] = 0;
  49507. this._rotMatrix.m[13] = 0;
  49508. this._rotMatrix.m[14] = 0;
  49509. this._rotMatrix.m[15] = 1.0;
  49510. };
  49511. /**
  49512. * Disposes the SPS.
  49513. */
  49514. SolidParticleSystem.prototype.dispose = function () {
  49515. this.mesh.dispose();
  49516. this.vars = null;
  49517. // drop references to internal big arrays for the GC
  49518. this._positions = null;
  49519. this._indices = null;
  49520. this._normals = null;
  49521. this._uvs = null;
  49522. this._colors = null;
  49523. this._indices32 = null;
  49524. this._positions32 = null;
  49525. this._normals32 = null;
  49526. this._fixedNormal32 = null;
  49527. this._uvs32 = null;
  49528. this._colors32 = null;
  49529. this.pickedParticles = null;
  49530. };
  49531. /**
  49532. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49533. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49534. * @returns the SPS.
  49535. */
  49536. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49537. if (!this._isVisibilityBoxLocked) {
  49538. this.mesh.refreshBoundingInfo();
  49539. }
  49540. return this;
  49541. };
  49542. /**
  49543. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49544. * @param size the size (float) of the visibility box
  49545. * note : this doesn't lock the SPS mesh bounding box.
  49546. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49547. */
  49548. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49549. var vis = size / 2;
  49550. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49551. };
  49552. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49553. /**
  49554. * Gets whether the SPS as always visible or not
  49555. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49556. */
  49557. get: function () {
  49558. return this._alwaysVisible;
  49559. },
  49560. /**
  49561. * Sets the SPS as always visible or not
  49562. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49563. */
  49564. set: function (val) {
  49565. this._alwaysVisible = val;
  49566. this.mesh.alwaysSelectAsActiveMesh = val;
  49567. },
  49568. enumerable: true,
  49569. configurable: true
  49570. });
  49571. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49572. /**
  49573. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49574. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49575. */
  49576. get: function () {
  49577. return this._isVisibilityBoxLocked;
  49578. },
  49579. /**
  49580. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49581. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49582. */
  49583. set: function (val) {
  49584. this._isVisibilityBoxLocked = val;
  49585. var boundingInfo = this.mesh.getBoundingInfo();
  49586. boundingInfo.isLocked = val;
  49587. },
  49588. enumerable: true,
  49589. configurable: true
  49590. });
  49591. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49592. /**
  49593. * Gets if `setParticles()` computes the particle rotations or not.
  49594. * Default value : true. The SPS is faster when it's set to false.
  49595. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49596. */
  49597. get: function () {
  49598. return this._computeParticleRotation;
  49599. },
  49600. /**
  49601. * Tells to `setParticles()` to compute the particle rotations or not.
  49602. * Default value : true. The SPS is faster when it's set to false.
  49603. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49604. */
  49605. set: function (val) {
  49606. this._computeParticleRotation = val;
  49607. },
  49608. enumerable: true,
  49609. configurable: true
  49610. });
  49611. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49612. /**
  49613. * Gets if `setParticles()` computes the particle colors or not.
  49614. * Default value : true. The SPS is faster when it's set to false.
  49615. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49616. */
  49617. get: function () {
  49618. return this._computeParticleColor;
  49619. },
  49620. /**
  49621. * Tells to `setParticles()` to compute the particle colors or not.
  49622. * Default value : true. The SPS is faster when it's set to false.
  49623. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49624. */
  49625. set: function (val) {
  49626. this._computeParticleColor = val;
  49627. },
  49628. enumerable: true,
  49629. configurable: true
  49630. });
  49631. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49632. /**
  49633. * Gets if `setParticles()` computes the particle textures or not.
  49634. * Default value : true. The SPS is faster when it's set to false.
  49635. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49636. */
  49637. get: function () {
  49638. return this._computeParticleTexture;
  49639. },
  49640. set: function (val) {
  49641. this._computeParticleTexture = val;
  49642. },
  49643. enumerable: true,
  49644. configurable: true
  49645. });
  49646. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49647. /**
  49648. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  49649. * Default value : false. The SPS is faster when it's set to false.
  49650. * Note : the particle custom vertex positions aren't stored values.
  49651. */
  49652. get: function () {
  49653. return this._computeParticleVertex;
  49654. },
  49655. /**
  49656. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49657. * Default value : false. The SPS is faster when it's set to false.
  49658. * Note : the particle custom vertex positions aren't stored values.
  49659. */
  49660. set: function (val) {
  49661. this._computeParticleVertex = val;
  49662. },
  49663. enumerable: true,
  49664. configurable: true
  49665. });
  49666. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49667. /**
  49668. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  49669. */
  49670. get: function () {
  49671. return this._computeBoundingBox;
  49672. },
  49673. /**
  49674. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49675. */
  49676. set: function (val) {
  49677. this._computeBoundingBox = val;
  49678. },
  49679. enumerable: true,
  49680. configurable: true
  49681. });
  49682. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  49683. /**
  49684. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  49685. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49686. * Default : `true`
  49687. */
  49688. get: function () {
  49689. return this._depthSortParticles;
  49690. },
  49691. /**
  49692. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  49693. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49694. * Default : `true`
  49695. */
  49696. set: function (val) {
  49697. this._depthSortParticles = val;
  49698. },
  49699. enumerable: true,
  49700. configurable: true
  49701. });
  49702. // =======================================================================
  49703. // Particle behavior logic
  49704. // these following methods may be overwritten by the user to fit his needs
  49705. /**
  49706. * This function does nothing. It may be overwritten to set all the particle first values.
  49707. * The SPS doesn't call this function, you may have to call it by your own.
  49708. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49709. */
  49710. SolidParticleSystem.prototype.initParticles = function () {
  49711. };
  49712. /**
  49713. * This function does nothing. It may be overwritten to recycle a particle.
  49714. * The SPS doesn't call this function, you may have to call it by your own.
  49715. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49716. * @param particle The particle to recycle
  49717. * @returns the recycled particle
  49718. */
  49719. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49720. return particle;
  49721. };
  49722. /**
  49723. * Updates a particle : this function should be overwritten by the user.
  49724. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49725. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49726. * @example : just set a particle position or velocity and recycle conditions
  49727. * @param particle The particle to update
  49728. * @returns the updated particle
  49729. */
  49730. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49731. return particle;
  49732. };
  49733. /**
  49734. * Updates a vertex of a particle : it can be overwritten by the user.
  49735. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49736. * @param particle the current particle
  49737. * @param vertex the current index of the current particle
  49738. * @param pt the index of the current vertex in the particle shape
  49739. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49740. * @example : just set a vertex particle position
  49741. * @returns the updated vertex
  49742. */
  49743. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49744. return vertex;
  49745. };
  49746. /**
  49747. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49748. * This does nothing and may be overwritten by the user.
  49749. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49750. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49751. * @param update the boolean update value actually passed to setParticles()
  49752. */
  49753. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49754. };
  49755. /**
  49756. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49757. * This will be passed three parameters.
  49758. * This does nothing and may be overwritten by the user.
  49759. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49760. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49761. * @param update the boolean update value actually passed to setParticles()
  49762. */
  49763. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49764. };
  49765. return SolidParticleSystem;
  49766. }());
  49767. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49768. })(BABYLON || (BABYLON = {}));
  49769. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49770. var BABYLON;
  49771. (function (BABYLON) {
  49772. var ShaderMaterial = /** @class */ (function (_super) {
  49773. __extends(ShaderMaterial, _super);
  49774. function ShaderMaterial(name, scene, shaderPath, options) {
  49775. var _this = _super.call(this, name, scene) || this;
  49776. _this._textures = {};
  49777. _this._textureArrays = {};
  49778. _this._floats = {};
  49779. _this._ints = {};
  49780. _this._floatsArrays = {};
  49781. _this._colors3 = {};
  49782. _this._colors3Arrays = {};
  49783. _this._colors4 = {};
  49784. _this._vectors2 = {};
  49785. _this._vectors3 = {};
  49786. _this._vectors4 = {};
  49787. _this._matrices = {};
  49788. _this._matrices3x3 = {};
  49789. _this._matrices2x2 = {};
  49790. _this._vectors2Arrays = {};
  49791. _this._vectors3Arrays = {};
  49792. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49793. _this._shaderPath = shaderPath;
  49794. options.needAlphaBlending = options.needAlphaBlending || false;
  49795. options.needAlphaTesting = options.needAlphaTesting || false;
  49796. options.attributes = options.attributes || ["position", "normal", "uv"];
  49797. options.uniforms = options.uniforms || ["worldViewProjection"];
  49798. options.uniformBuffers = options.uniformBuffers || [];
  49799. options.samplers = options.samplers || [];
  49800. options.defines = options.defines || [];
  49801. _this._options = options;
  49802. return _this;
  49803. }
  49804. ShaderMaterial.prototype.getClassName = function () {
  49805. return "ShaderMaterial";
  49806. };
  49807. ShaderMaterial.prototype.needAlphaBlending = function () {
  49808. return this._options.needAlphaBlending;
  49809. };
  49810. ShaderMaterial.prototype.needAlphaTesting = function () {
  49811. return this._options.needAlphaTesting;
  49812. };
  49813. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49814. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49815. this._options.uniforms.push(uniformName);
  49816. }
  49817. };
  49818. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49819. if (this._options.samplers.indexOf(name) === -1) {
  49820. this._options.samplers.push(name);
  49821. }
  49822. this._textures[name] = texture;
  49823. return this;
  49824. };
  49825. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49826. if (this._options.samplers.indexOf(name) === -1) {
  49827. this._options.samplers.push(name);
  49828. }
  49829. this._checkUniform(name);
  49830. this._textureArrays[name] = textures;
  49831. return this;
  49832. };
  49833. ShaderMaterial.prototype.setFloat = function (name, value) {
  49834. this._checkUniform(name);
  49835. this._floats[name] = value;
  49836. return this;
  49837. };
  49838. ShaderMaterial.prototype.setInt = function (name, value) {
  49839. this._checkUniform(name);
  49840. this._ints[name] = value;
  49841. return this;
  49842. };
  49843. ShaderMaterial.prototype.setFloats = function (name, value) {
  49844. this._checkUniform(name);
  49845. this._floatsArrays[name] = value;
  49846. return this;
  49847. };
  49848. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49849. this._checkUniform(name);
  49850. this._colors3[name] = value;
  49851. return this;
  49852. };
  49853. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  49854. this._checkUniform(name);
  49855. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  49856. color.toArray(arr, arr.length);
  49857. return arr;
  49858. }, []);
  49859. return this;
  49860. };
  49861. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49862. this._checkUniform(name);
  49863. this._colors4[name] = value;
  49864. return this;
  49865. };
  49866. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49867. this._checkUniform(name);
  49868. this._vectors2[name] = value;
  49869. return this;
  49870. };
  49871. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49872. this._checkUniform(name);
  49873. this._vectors3[name] = value;
  49874. return this;
  49875. };
  49876. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49877. this._checkUniform(name);
  49878. this._vectors4[name] = value;
  49879. return this;
  49880. };
  49881. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49882. this._checkUniform(name);
  49883. this._matrices[name] = value;
  49884. return this;
  49885. };
  49886. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49887. this._checkUniform(name);
  49888. this._matrices3x3[name] = value;
  49889. return this;
  49890. };
  49891. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49892. this._checkUniform(name);
  49893. this._matrices2x2[name] = value;
  49894. return this;
  49895. };
  49896. ShaderMaterial.prototype.setArray2 = function (name, value) {
  49897. this._checkUniform(name);
  49898. this._vectors2Arrays[name] = value;
  49899. return this;
  49900. };
  49901. ShaderMaterial.prototype.setArray3 = function (name, value) {
  49902. this._checkUniform(name);
  49903. this._vectors3Arrays[name] = value;
  49904. return this;
  49905. };
  49906. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  49907. if (!mesh) {
  49908. return true;
  49909. }
  49910. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  49911. return false;
  49912. }
  49913. return false;
  49914. };
  49915. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49916. var scene = this.getScene();
  49917. var engine = scene.getEngine();
  49918. if (!this.checkReadyOnEveryCall) {
  49919. if (this._renderId === scene.getRenderId()) {
  49920. if (this._checkCache(scene, mesh, useInstances)) {
  49921. return true;
  49922. }
  49923. }
  49924. }
  49925. // Instances
  49926. var defines = [];
  49927. var attribs = [];
  49928. var fallbacks = new BABYLON.EffectFallbacks();
  49929. if (useInstances) {
  49930. defines.push("#define INSTANCES");
  49931. }
  49932. for (var index = 0; index < this._options.defines.length; index++) {
  49933. defines.push(this._options.defines[index]);
  49934. }
  49935. for (var index = 0; index < this._options.attributes.length; index++) {
  49936. attribs.push(this._options.attributes[index]);
  49937. }
  49938. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  49939. attribs.push(BABYLON.VertexBuffer.ColorKind);
  49940. defines.push("#define VERTEXCOLOR");
  49941. }
  49942. // Bones
  49943. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  49944. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49945. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49946. if (mesh.numBoneInfluencers > 4) {
  49947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49949. }
  49950. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49951. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49952. fallbacks.addCPUSkinningFallback(0, mesh);
  49953. if (this._options.uniforms.indexOf("mBones") === -1) {
  49954. this._options.uniforms.push("mBones");
  49955. }
  49956. }
  49957. else {
  49958. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49959. }
  49960. // Textures
  49961. for (var name in this._textures) {
  49962. if (!this._textures[name].isReady()) {
  49963. return false;
  49964. }
  49965. }
  49966. // Alpha test
  49967. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  49968. defines.push("#define ALPHATEST");
  49969. }
  49970. var previousEffect = this._effect;
  49971. var join = defines.join("\n");
  49972. this._effect = engine.createEffect(this._shaderPath, {
  49973. attributes: attribs,
  49974. uniformsNames: this._options.uniforms,
  49975. uniformBuffersNames: this._options.uniformBuffers,
  49976. samplers: this._options.samplers,
  49977. defines: join,
  49978. fallbacks: fallbacks,
  49979. onCompiled: this.onCompiled,
  49980. onError: this.onError
  49981. }, engine);
  49982. if (!this._effect.isReady()) {
  49983. return false;
  49984. }
  49985. if (previousEffect !== this._effect) {
  49986. scene.resetCachedMaterial();
  49987. }
  49988. this._renderId = scene.getRenderId();
  49989. return true;
  49990. };
  49991. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49992. var scene = this.getScene();
  49993. if (!this._effect) {
  49994. return;
  49995. }
  49996. if (this._options.uniforms.indexOf("world") !== -1) {
  49997. this._effect.setMatrix("world", world);
  49998. }
  49999. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50000. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50001. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50002. }
  50003. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50004. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50005. }
  50006. };
  50007. ShaderMaterial.prototype.bind = function (world, mesh) {
  50008. // Std values
  50009. this.bindOnlyWorldMatrix(world);
  50010. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50011. if (this._options.uniforms.indexOf("view") !== -1) {
  50012. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50013. }
  50014. if (this._options.uniforms.indexOf("projection") !== -1) {
  50015. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50016. }
  50017. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50018. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50019. }
  50020. // Bones
  50021. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50022. var name;
  50023. // Texture
  50024. for (name in this._textures) {
  50025. this._effect.setTexture(name, this._textures[name]);
  50026. }
  50027. // Texture arrays
  50028. for (name in this._textureArrays) {
  50029. this._effect.setTextureArray(name, this._textureArrays[name]);
  50030. }
  50031. // Int
  50032. for (name in this._ints) {
  50033. this._effect.setInt(name, this._ints[name]);
  50034. }
  50035. // Float
  50036. for (name in this._floats) {
  50037. this._effect.setFloat(name, this._floats[name]);
  50038. }
  50039. // Floats
  50040. for (name in this._floatsArrays) {
  50041. this._effect.setArray(name, this._floatsArrays[name]);
  50042. }
  50043. // Color3
  50044. for (name in this._colors3) {
  50045. this._effect.setColor3(name, this._colors3[name]);
  50046. }
  50047. for (name in this._colors3Arrays) {
  50048. this._effect.setArray3(name, this._colors3Arrays[name]);
  50049. }
  50050. // Color4
  50051. for (name in this._colors4) {
  50052. var color = this._colors4[name];
  50053. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50054. }
  50055. // Vector2
  50056. for (name in this._vectors2) {
  50057. this._effect.setVector2(name, this._vectors2[name]);
  50058. }
  50059. // Vector3
  50060. for (name in this._vectors3) {
  50061. this._effect.setVector3(name, this._vectors3[name]);
  50062. }
  50063. // Vector4
  50064. for (name in this._vectors4) {
  50065. this._effect.setVector4(name, this._vectors4[name]);
  50066. }
  50067. // Matrix
  50068. for (name in this._matrices) {
  50069. this._effect.setMatrix(name, this._matrices[name]);
  50070. }
  50071. // Matrix 3x3
  50072. for (name in this._matrices3x3) {
  50073. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  50074. }
  50075. // Matrix 2x2
  50076. for (name in this._matrices2x2) {
  50077. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  50078. }
  50079. // Vector2Array
  50080. for (name in this._vectors2Arrays) {
  50081. this._effect.setArray2(name, this._vectors2Arrays[name]);
  50082. }
  50083. // Vector3Array
  50084. for (name in this._vectors3Arrays) {
  50085. this._effect.setArray3(name, this._vectors3Arrays[name]);
  50086. }
  50087. }
  50088. this._afterBind(mesh);
  50089. };
  50090. ShaderMaterial.prototype.getActiveTextures = function () {
  50091. var activeTextures = _super.prototype.getActiveTextures.call(this);
  50092. for (var name in this._textures) {
  50093. activeTextures.push(this._textures[name]);
  50094. }
  50095. for (var name in this._textureArrays) {
  50096. var array = this._textureArrays[name];
  50097. for (var index = 0; index < array.length; index++) {
  50098. activeTextures.push(array[index]);
  50099. }
  50100. }
  50101. return activeTextures;
  50102. };
  50103. ShaderMaterial.prototype.hasTexture = function (texture) {
  50104. if (_super.prototype.hasTexture.call(this, texture)) {
  50105. return true;
  50106. }
  50107. for (var name in this._textures) {
  50108. if (this._textures[name] === texture) {
  50109. return true;
  50110. }
  50111. }
  50112. for (var name in this._textureArrays) {
  50113. var array = this._textureArrays[name];
  50114. for (var index = 0; index < array.length; index++) {
  50115. if (array[index] === texture) {
  50116. return true;
  50117. }
  50118. }
  50119. }
  50120. return false;
  50121. };
  50122. ShaderMaterial.prototype.clone = function (name) {
  50123. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  50124. return newShaderMaterial;
  50125. };
  50126. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50127. if (forceDisposeTextures) {
  50128. var name;
  50129. for (name in this._textures) {
  50130. this._textures[name].dispose();
  50131. }
  50132. for (name in this._textureArrays) {
  50133. var array = this._textureArrays[name];
  50134. for (var index = 0; index < array.length; index++) {
  50135. array[index].dispose();
  50136. }
  50137. }
  50138. }
  50139. this._textures = {};
  50140. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50141. };
  50142. ShaderMaterial.prototype.serialize = function () {
  50143. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50144. serializationObject.customType = "BABYLON.ShaderMaterial";
  50145. serializationObject.options = this._options;
  50146. serializationObject.shaderPath = this._shaderPath;
  50147. var name;
  50148. // Texture
  50149. serializationObject.textures = {};
  50150. for (name in this._textures) {
  50151. serializationObject.textures[name] = this._textures[name].serialize();
  50152. }
  50153. // Texture arrays
  50154. serializationObject.textureArrays = {};
  50155. for (name in this._textureArrays) {
  50156. serializationObject.textureArrays[name] = [];
  50157. var array = this._textureArrays[name];
  50158. for (var index = 0; index < array.length; index++) {
  50159. serializationObject.textureArrays[name].push(array[index].serialize());
  50160. }
  50161. }
  50162. // Float
  50163. serializationObject.floats = {};
  50164. for (name in this._floats) {
  50165. serializationObject.floats[name] = this._floats[name];
  50166. }
  50167. // Float s
  50168. serializationObject.FloatArrays = {};
  50169. for (name in this._floatsArrays) {
  50170. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  50171. }
  50172. // Color3
  50173. serializationObject.colors3 = {};
  50174. for (name in this._colors3) {
  50175. serializationObject.colors3[name] = this._colors3[name].asArray();
  50176. }
  50177. // Color3 array
  50178. serializationObject.colors3Arrays = {};
  50179. for (name in this._colors3Arrays) {
  50180. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50181. }
  50182. // Color4
  50183. serializationObject.colors4 = {};
  50184. for (name in this._colors4) {
  50185. serializationObject.colors4[name] = this._colors4[name].asArray();
  50186. }
  50187. // Vector2
  50188. serializationObject.vectors2 = {};
  50189. for (name in this._vectors2) {
  50190. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50191. }
  50192. // Vector3
  50193. serializationObject.vectors3 = {};
  50194. for (name in this._vectors3) {
  50195. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50196. }
  50197. // Vector4
  50198. serializationObject.vectors4 = {};
  50199. for (name in this._vectors4) {
  50200. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50201. }
  50202. // Matrix
  50203. serializationObject.matrices = {};
  50204. for (name in this._matrices) {
  50205. serializationObject.matrices[name] = this._matrices[name].asArray();
  50206. }
  50207. // Matrix 3x3
  50208. serializationObject.matrices3x3 = {};
  50209. for (name in this._matrices3x3) {
  50210. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50211. }
  50212. // Matrix 2x2
  50213. serializationObject.matrices2x2 = {};
  50214. for (name in this._matrices2x2) {
  50215. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50216. }
  50217. // Vector2Array
  50218. serializationObject.vectors2Arrays = {};
  50219. for (name in this._vectors2Arrays) {
  50220. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50221. }
  50222. // Vector3Array
  50223. serializationObject.vectors3Arrays = {};
  50224. for (name in this._vectors3Arrays) {
  50225. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50226. }
  50227. return serializationObject;
  50228. };
  50229. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50230. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50231. var name;
  50232. // Texture
  50233. for (name in source.textures) {
  50234. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50235. }
  50236. // Texture arrays
  50237. for (name in source.textureArrays) {
  50238. var array = source.textureArrays[name];
  50239. var textureArray = new Array();
  50240. for (var index = 0; index < array.length; index++) {
  50241. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50242. }
  50243. material.setTextureArray(name, textureArray);
  50244. }
  50245. // Float
  50246. for (name in source.floats) {
  50247. material.setFloat(name, source.floats[name]);
  50248. }
  50249. // Float s
  50250. for (name in source.floatsArrays) {
  50251. material.setFloats(name, source.floatsArrays[name]);
  50252. }
  50253. // Color3
  50254. for (name in source.colors3) {
  50255. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50256. }
  50257. // Color3 arrays
  50258. for (name in source.colors3Arrays) {
  50259. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50260. if (i % 3 === 0) {
  50261. arr.push([num]);
  50262. }
  50263. else {
  50264. arr[arr.length - 1].push(num);
  50265. }
  50266. return arr;
  50267. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50268. material.setColor3Array(name, colors);
  50269. }
  50270. // Color4
  50271. for (name in source.colors4) {
  50272. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50273. }
  50274. // Vector2
  50275. for (name in source.vectors2) {
  50276. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50277. }
  50278. // Vector3
  50279. for (name in source.vectors3) {
  50280. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50281. }
  50282. // Vector4
  50283. for (name in source.vectors4) {
  50284. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50285. }
  50286. // Matrix
  50287. for (name in source.matrices) {
  50288. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50289. }
  50290. // Matrix 3x3
  50291. for (name in source.matrices3x3) {
  50292. material.setMatrix3x3(name, source.matrices3x3[name]);
  50293. }
  50294. // Matrix 2x2
  50295. for (name in source.matrices2x2) {
  50296. material.setMatrix2x2(name, source.matrices2x2[name]);
  50297. }
  50298. // Vector2Array
  50299. for (name in source.vectors2Arrays) {
  50300. material.setArray2(name, source.vectors2Arrays[name]);
  50301. }
  50302. // Vector3Array
  50303. for (name in source.vectors3Arrays) {
  50304. material.setArray3(name, source.vectors3Arrays[name]);
  50305. }
  50306. return material;
  50307. };
  50308. return ShaderMaterial;
  50309. }(BABYLON.Material));
  50310. BABYLON.ShaderMaterial = ShaderMaterial;
  50311. })(BABYLON || (BABYLON = {}));
  50312. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50313. var BABYLON;
  50314. (function (BABYLON) {
  50315. var GroundMesh = /** @class */ (function (_super) {
  50316. __extends(GroundMesh, _super);
  50317. function GroundMesh(name, scene) {
  50318. var _this = _super.call(this, name, scene) || this;
  50319. _this.generateOctree = false;
  50320. return _this;
  50321. }
  50322. GroundMesh.prototype.getClassName = function () {
  50323. return "GroundMesh";
  50324. };
  50325. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50326. get: function () {
  50327. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50328. },
  50329. enumerable: true,
  50330. configurable: true
  50331. });
  50332. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50333. get: function () {
  50334. return this._subdivisionsX;
  50335. },
  50336. enumerable: true,
  50337. configurable: true
  50338. });
  50339. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50340. get: function () {
  50341. return this._subdivisionsY;
  50342. },
  50343. enumerable: true,
  50344. configurable: true
  50345. });
  50346. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50347. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50348. this._subdivisionsX = chunksCount;
  50349. this._subdivisionsY = chunksCount;
  50350. this.subdivide(chunksCount);
  50351. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50352. };
  50353. /**
  50354. * Returns a height (y) value in the Worl system :
  50355. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50356. * Returns the ground y position if (x, z) are outside the ground surface.
  50357. */
  50358. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50359. var world = this.getWorldMatrix();
  50360. var invMat = BABYLON.Tmp.Matrix[5];
  50361. world.invertToRef(invMat);
  50362. var tmpVect = BABYLON.Tmp.Vector3[8];
  50363. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50364. x = tmpVect.x;
  50365. z = tmpVect.z;
  50366. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50367. return this.position.y;
  50368. }
  50369. if (!this._heightQuads || this._heightQuads.length == 0) {
  50370. this._initHeightQuads();
  50371. this._computeHeightQuads();
  50372. }
  50373. var facet = this._getFacetAt(x, z);
  50374. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50375. // return y in the World system
  50376. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50377. return tmpVect.y;
  50378. };
  50379. /**
  50380. * Returns a normalized vector (Vector3) orthogonal to the ground
  50381. * at the ground coordinates (x, z) expressed in the World system.
  50382. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50383. */
  50384. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50385. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50386. this.getNormalAtCoordinatesToRef(x, z, normal);
  50387. return normal;
  50388. };
  50389. /**
  50390. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50391. * at the ground coordinates (x, z) expressed in the World system.
  50392. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50393. * Returns the GroundMesh.
  50394. */
  50395. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50396. var world = this.getWorldMatrix();
  50397. var tmpMat = BABYLON.Tmp.Matrix[5];
  50398. world.invertToRef(tmpMat);
  50399. var tmpVect = BABYLON.Tmp.Vector3[8];
  50400. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50401. x = tmpVect.x;
  50402. z = tmpVect.z;
  50403. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50404. return this;
  50405. }
  50406. if (!this._heightQuads || this._heightQuads.length == 0) {
  50407. this._initHeightQuads();
  50408. this._computeHeightQuads();
  50409. }
  50410. var facet = this._getFacetAt(x, z);
  50411. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  50412. return this;
  50413. };
  50414. /**
  50415. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  50416. * if the ground has been updated.
  50417. * This can be used in the render loop.
  50418. * Returns the GroundMesh.
  50419. */
  50420. GroundMesh.prototype.updateCoordinateHeights = function () {
  50421. if (!this._heightQuads || this._heightQuads.length == 0) {
  50422. this._initHeightQuads();
  50423. }
  50424. this._computeHeightQuads();
  50425. return this;
  50426. };
  50427. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  50428. GroundMesh.prototype._getFacetAt = function (x, z) {
  50429. // retrieve col and row from x, z coordinates in the ground local system
  50430. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  50431. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  50432. var quad = this._heightQuads[row * this._subdivisionsX + col];
  50433. var facet;
  50434. if (z < quad.slope.x * x + quad.slope.y) {
  50435. facet = quad.facet1;
  50436. }
  50437. else {
  50438. facet = quad.facet2;
  50439. }
  50440. return facet;
  50441. };
  50442. // Creates and populates the heightMap array with "facet" elements :
  50443. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  50444. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50445. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50446. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50447. // Returns the GroundMesh.
  50448. GroundMesh.prototype._initHeightQuads = function () {
  50449. var subdivisionsX = this._subdivisionsX;
  50450. var subdivisionsY = this._subdivisionsY;
  50451. this._heightQuads = new Array();
  50452. for (var row = 0; row < subdivisionsY; row++) {
  50453. for (var col = 0; col < subdivisionsX; col++) {
  50454. 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) };
  50455. this._heightQuads[row * subdivisionsX + col] = quad;
  50456. }
  50457. }
  50458. return this;
  50459. };
  50460. // Compute each quad element values and update the the heightMap array :
  50461. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50462. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50463. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50464. // Returns the GroundMesh.
  50465. GroundMesh.prototype._computeHeightQuads = function () {
  50466. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50467. if (!positions) {
  50468. return this;
  50469. }
  50470. var v1 = BABYLON.Tmp.Vector3[3];
  50471. var v2 = BABYLON.Tmp.Vector3[2];
  50472. var v3 = BABYLON.Tmp.Vector3[1];
  50473. var v4 = BABYLON.Tmp.Vector3[0];
  50474. var v1v2 = BABYLON.Tmp.Vector3[4];
  50475. var v1v3 = BABYLON.Tmp.Vector3[5];
  50476. var v1v4 = BABYLON.Tmp.Vector3[6];
  50477. var norm1 = BABYLON.Tmp.Vector3[7];
  50478. var norm2 = BABYLON.Tmp.Vector3[8];
  50479. var i = 0;
  50480. var j = 0;
  50481. var k = 0;
  50482. var cd = 0; // 2D slope coefficient : z = cd * x + h
  50483. var h = 0;
  50484. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  50485. var d2 = 0;
  50486. var subdivisionsX = this._subdivisionsX;
  50487. var subdivisionsY = this._subdivisionsY;
  50488. for (var row = 0; row < subdivisionsY; row++) {
  50489. for (var col = 0; col < subdivisionsX; col++) {
  50490. i = col * 3;
  50491. j = row * (subdivisionsX + 1) * 3;
  50492. k = (row + 1) * (subdivisionsX + 1) * 3;
  50493. v1.x = positions[j + i];
  50494. v1.y = positions[j + i + 1];
  50495. v1.z = positions[j + i + 2];
  50496. v2.x = positions[j + i + 3];
  50497. v2.y = positions[j + i + 4];
  50498. v2.z = positions[j + i + 5];
  50499. v3.x = positions[k + i];
  50500. v3.y = positions[k + i + 1];
  50501. v3.z = positions[k + i + 2];
  50502. v4.x = positions[k + i + 3];
  50503. v4.y = positions[k + i + 4];
  50504. v4.z = positions[k + i + 5];
  50505. // 2D slope V1V4
  50506. cd = (v4.z - v1.z) / (v4.x - v1.x);
  50507. h = v1.z - cd * v1.x; // v1 belongs to the slope
  50508. // facet equations :
  50509. // we compute each facet normal vector
  50510. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  50511. // we compute the value d by applying the equation to v1 which belongs to the plane
  50512. // then we store the facet equation in a Vector4
  50513. v2.subtractToRef(v1, v1v2);
  50514. v3.subtractToRef(v1, v1v3);
  50515. v4.subtractToRef(v1, v1v4);
  50516. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  50517. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  50518. norm1.normalize();
  50519. norm2.normalize();
  50520. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  50521. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  50522. var quad = this._heightQuads[row * subdivisionsX + col];
  50523. quad.slope.copyFromFloats(cd, h);
  50524. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  50525. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  50526. }
  50527. }
  50528. return this;
  50529. };
  50530. GroundMesh.prototype.serialize = function (serializationObject) {
  50531. _super.prototype.serialize.call(this, serializationObject);
  50532. serializationObject.subdivisionsX = this._subdivisionsX;
  50533. serializationObject.subdivisionsY = this._subdivisionsY;
  50534. serializationObject.minX = this._minX;
  50535. serializationObject.maxX = this._maxX;
  50536. serializationObject.minZ = this._minZ;
  50537. serializationObject.maxZ = this._maxZ;
  50538. serializationObject.width = this._width;
  50539. serializationObject.height = this._height;
  50540. };
  50541. GroundMesh.Parse = function (parsedMesh, scene) {
  50542. var result = new GroundMesh(parsedMesh.name, scene);
  50543. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  50544. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  50545. result._minX = parsedMesh.minX;
  50546. result._maxX = parsedMesh.maxX;
  50547. result._minZ = parsedMesh.minZ;
  50548. result._maxZ = parsedMesh.maxZ;
  50549. result._width = parsedMesh.width;
  50550. result._height = parsedMesh.height;
  50551. return result;
  50552. };
  50553. return GroundMesh;
  50554. }(BABYLON.Mesh));
  50555. BABYLON.GroundMesh = GroundMesh;
  50556. })(BABYLON || (BABYLON = {}));
  50557. //# sourceMappingURL=babylon.groundMesh.js.map
  50558. var BABYLON;
  50559. (function (BABYLON) {
  50560. /**
  50561. * Creates an instance based on a source mesh.
  50562. */
  50563. var InstancedMesh = /** @class */ (function (_super) {
  50564. __extends(InstancedMesh, _super);
  50565. function InstancedMesh(name, source) {
  50566. var _this = _super.call(this, name, source.getScene()) || this;
  50567. source.instances.push(_this);
  50568. _this._sourceMesh = source;
  50569. _this.position.copyFrom(source.position);
  50570. _this.rotation.copyFrom(source.rotation);
  50571. _this.scaling.copyFrom(source.scaling);
  50572. if (source.rotationQuaternion) {
  50573. _this.rotationQuaternion = source.rotationQuaternion.clone();
  50574. }
  50575. _this.infiniteDistance = source.infiniteDistance;
  50576. _this.setPivotMatrix(source.getPivotMatrix());
  50577. _this.refreshBoundingInfo();
  50578. _this._syncSubMeshes();
  50579. return _this;
  50580. }
  50581. /**
  50582. * Returns the string "InstancedMesh".
  50583. */
  50584. InstancedMesh.prototype.getClassName = function () {
  50585. return "InstancedMesh";
  50586. };
  50587. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  50588. // Methods
  50589. get: function () {
  50590. return this._sourceMesh.receiveShadows;
  50591. },
  50592. enumerable: true,
  50593. configurable: true
  50594. });
  50595. Object.defineProperty(InstancedMesh.prototype, "material", {
  50596. get: function () {
  50597. return this._sourceMesh.material;
  50598. },
  50599. enumerable: true,
  50600. configurable: true
  50601. });
  50602. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  50603. get: function () {
  50604. return this._sourceMesh.visibility;
  50605. },
  50606. enumerable: true,
  50607. configurable: true
  50608. });
  50609. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  50610. get: function () {
  50611. return this._sourceMesh.skeleton;
  50612. },
  50613. enumerable: true,
  50614. configurable: true
  50615. });
  50616. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  50617. get: function () {
  50618. return this._sourceMesh.renderingGroupId;
  50619. },
  50620. enumerable: true,
  50621. configurable: true
  50622. });
  50623. /**
  50624. * Returns the total number of vertices (integer).
  50625. */
  50626. InstancedMesh.prototype.getTotalVertices = function () {
  50627. return this._sourceMesh.getTotalVertices();
  50628. };
  50629. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  50630. get: function () {
  50631. return this._sourceMesh;
  50632. },
  50633. enumerable: true,
  50634. configurable: true
  50635. });
  50636. /**
  50637. * Is this node ready to be used/rendered
  50638. * @return {boolean} is it ready
  50639. */
  50640. InstancedMesh.prototype.isReady = function () {
  50641. return this._sourceMesh.isReady(true);
  50642. };
  50643. /**
  50644. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  50645. */
  50646. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  50647. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  50648. };
  50649. /**
  50650. * Sets the vertex data of the mesh geometry for the requested `kind`.
  50651. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  50652. * The `data` are either a numeric array either a Float32Array.
  50653. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  50654. * 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).
  50655. * Note that a new underlying VertexBuffer object is created each call.
  50656. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  50657. *
  50658. * Possible `kind` values :
  50659. * - BABYLON.VertexBuffer.PositionKind
  50660. * - BABYLON.VertexBuffer.UVKind
  50661. * - BABYLON.VertexBuffer.UV2Kind
  50662. * - BABYLON.VertexBuffer.UV3Kind
  50663. * - BABYLON.VertexBuffer.UV4Kind
  50664. * - BABYLON.VertexBuffer.UV5Kind
  50665. * - BABYLON.VertexBuffer.UV6Kind
  50666. * - BABYLON.VertexBuffer.ColorKind
  50667. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50668. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50669. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50670. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50671. *
  50672. * Returns the Mesh.
  50673. */
  50674. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  50675. if (this.sourceMesh) {
  50676. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  50677. }
  50678. return this.sourceMesh;
  50679. };
  50680. /**
  50681. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  50682. * If the mesh has no geometry, it is simply returned as it is.
  50683. * The `data` are either a numeric array either a Float32Array.
  50684. * No new underlying VertexBuffer object is created.
  50685. * 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.
  50686. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  50687. *
  50688. * Possible `kind` values :
  50689. * - BABYLON.VertexBuffer.PositionKind
  50690. * - BABYLON.VertexBuffer.UVKind
  50691. * - BABYLON.VertexBuffer.UV2Kind
  50692. * - BABYLON.VertexBuffer.UV3Kind
  50693. * - BABYLON.VertexBuffer.UV4Kind
  50694. * - BABYLON.VertexBuffer.UV5Kind
  50695. * - BABYLON.VertexBuffer.UV6Kind
  50696. * - BABYLON.VertexBuffer.ColorKind
  50697. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50698. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50699. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50700. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50701. *
  50702. * Returns the Mesh.
  50703. */
  50704. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  50705. if (this.sourceMesh) {
  50706. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  50707. }
  50708. return this.sourceMesh;
  50709. };
  50710. /**
  50711. * Sets the mesh indices.
  50712. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  50713. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  50714. * This method creates a new index buffer each call.
  50715. * Returns the Mesh.
  50716. */
  50717. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  50718. if (totalVertices === void 0) { totalVertices = null; }
  50719. if (this.sourceMesh) {
  50720. this.sourceMesh.setIndices(indices, totalVertices);
  50721. }
  50722. return this.sourceMesh;
  50723. };
  50724. /**
  50725. * Boolean : True if the mesh owns the requested kind of data.
  50726. */
  50727. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  50728. return this._sourceMesh.isVerticesDataPresent(kind);
  50729. };
  50730. /**
  50731. * Returns an array of indices (IndicesArray).
  50732. */
  50733. InstancedMesh.prototype.getIndices = function () {
  50734. return this._sourceMesh.getIndices();
  50735. };
  50736. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  50737. get: function () {
  50738. return this._sourceMesh._positions;
  50739. },
  50740. enumerable: true,
  50741. configurable: true
  50742. });
  50743. /**
  50744. * Sets a new updated BoundingInfo to the mesh.
  50745. * Returns the mesh.
  50746. */
  50747. InstancedMesh.prototype.refreshBoundingInfo = function () {
  50748. var meshBB = this._sourceMesh.getBoundingInfo();
  50749. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  50750. this._updateBoundingInfo();
  50751. return this;
  50752. };
  50753. InstancedMesh.prototype._preActivate = function () {
  50754. if (this._currentLOD) {
  50755. this._currentLOD._preActivate();
  50756. }
  50757. return this;
  50758. };
  50759. InstancedMesh.prototype._activate = function (renderId) {
  50760. if (this._currentLOD) {
  50761. this._currentLOD._registerInstanceForRenderId(this, renderId);
  50762. }
  50763. return this;
  50764. };
  50765. /**
  50766. * Returns the current associated LOD AbstractMesh.
  50767. */
  50768. InstancedMesh.prototype.getLOD = function (camera) {
  50769. if (!camera) {
  50770. return this;
  50771. }
  50772. var boundingInfo = this.getBoundingInfo();
  50773. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  50774. if (this._currentLOD === this.sourceMesh) {
  50775. return this;
  50776. }
  50777. return this._currentLOD;
  50778. };
  50779. InstancedMesh.prototype._syncSubMeshes = function () {
  50780. this.releaseSubMeshes();
  50781. if (this._sourceMesh.subMeshes) {
  50782. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  50783. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  50784. }
  50785. }
  50786. return this;
  50787. };
  50788. InstancedMesh.prototype._generatePointsArray = function () {
  50789. return this._sourceMesh._generatePointsArray();
  50790. };
  50791. /**
  50792. * Creates a new InstancedMesh from the current mesh.
  50793. * - name (string) : the cloned mesh name
  50794. * - newParent (optional Node) : the optional Node to parent the clone to.
  50795. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  50796. *
  50797. * Returns the clone.
  50798. */
  50799. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50800. var result = this._sourceMesh.createInstance(name);
  50801. // Deep copy
  50802. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  50803. // Bounding info
  50804. this.refreshBoundingInfo();
  50805. // Parent
  50806. if (newParent) {
  50807. result.parent = newParent;
  50808. }
  50809. if (!doNotCloneChildren) {
  50810. // Children
  50811. for (var index = 0; index < this.getScene().meshes.length; index++) {
  50812. var mesh = this.getScene().meshes[index];
  50813. if (mesh.parent === this) {
  50814. mesh.clone(mesh.name, result);
  50815. }
  50816. }
  50817. }
  50818. result.computeWorldMatrix(true);
  50819. return result;
  50820. };
  50821. /**
  50822. * Disposes the InstancedMesh.
  50823. * Returns nothing.
  50824. */
  50825. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  50826. // Remove from mesh
  50827. var index = this._sourceMesh.instances.indexOf(this);
  50828. this._sourceMesh.instances.splice(index, 1);
  50829. _super.prototype.dispose.call(this, doNotRecurse);
  50830. };
  50831. return InstancedMesh;
  50832. }(BABYLON.AbstractMesh));
  50833. BABYLON.InstancedMesh = InstancedMesh;
  50834. })(BABYLON || (BABYLON = {}));
  50835. //# sourceMappingURL=babylon.instancedMesh.js.map
  50836. var BABYLON;
  50837. (function (BABYLON) {
  50838. var LinesMesh = /** @class */ (function (_super) {
  50839. __extends(LinesMesh, _super);
  50840. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  50841. if (scene === void 0) { scene = null; }
  50842. if (parent === void 0) { parent = null; }
  50843. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  50844. _this.useVertexColor = useVertexColor;
  50845. _this.useVertexAlpha = useVertexAlpha;
  50846. _this.color = new BABYLON.Color3(1, 1, 1);
  50847. _this.alpha = 1;
  50848. if (source) {
  50849. _this.color = source.color.clone();
  50850. _this.alpha = source.alpha;
  50851. _this.useVertexColor = source.useVertexColor;
  50852. _this.useVertexAlpha = source.useVertexAlpha;
  50853. }
  50854. _this._intersectionThreshold = 0.1;
  50855. var defines = [];
  50856. var options = {
  50857. attributes: [BABYLON.VertexBuffer.PositionKind],
  50858. uniforms: ["world", "viewProjection"],
  50859. needAlphaBlending: true,
  50860. defines: defines
  50861. };
  50862. if (useVertexAlpha === false) {
  50863. options.needAlphaBlending = false;
  50864. }
  50865. if (!useVertexColor) {
  50866. options.uniforms.push("color");
  50867. }
  50868. else {
  50869. options.defines.push("#define VERTEXCOLOR");
  50870. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  50871. }
  50872. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  50873. return _this;
  50874. }
  50875. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  50876. /**
  50877. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50878. * This margin is expressed in world space coordinates, so its value may vary.
  50879. * Default value is 0.1
  50880. * @returns the intersection Threshold value.
  50881. */
  50882. get: function () {
  50883. return this._intersectionThreshold;
  50884. },
  50885. /**
  50886. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50887. * This margin is expressed in world space coordinates, so its value may vary.
  50888. * @param value the new threshold to apply
  50889. */
  50890. set: function (value) {
  50891. if (this._intersectionThreshold === value) {
  50892. return;
  50893. }
  50894. this._intersectionThreshold = value;
  50895. if (this.geometry) {
  50896. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  50897. }
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. /**
  50903. * Returns the string "LineMesh"
  50904. */
  50905. LinesMesh.prototype.getClassName = function () {
  50906. return "LinesMesh";
  50907. };
  50908. Object.defineProperty(LinesMesh.prototype, "material", {
  50909. get: function () {
  50910. return this._colorShader;
  50911. },
  50912. set: function (value) {
  50913. // Do nothing
  50914. },
  50915. enumerable: true,
  50916. configurable: true
  50917. });
  50918. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  50919. get: function () {
  50920. return false;
  50921. },
  50922. enumerable: true,
  50923. configurable: true
  50924. });
  50925. LinesMesh.prototype.createInstance = function (name) {
  50926. throw new Error("LinesMeshes do not support createInstance.");
  50927. };
  50928. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  50929. if (!this._geometry) {
  50930. return this;
  50931. }
  50932. // VBOs
  50933. this._geometry._bind(this._colorShader.getEffect());
  50934. // Color
  50935. if (!this.useVertexColor) {
  50936. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  50937. }
  50938. return this;
  50939. };
  50940. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  50941. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  50942. return this;
  50943. }
  50944. var engine = this.getScene().getEngine();
  50945. // Draw order
  50946. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  50947. return this;
  50948. };
  50949. LinesMesh.prototype.dispose = function (doNotRecurse) {
  50950. this._colorShader.dispose();
  50951. _super.prototype.dispose.call(this, doNotRecurse);
  50952. };
  50953. /**
  50954. * Returns a new LineMesh object cloned from the current one.
  50955. */
  50956. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50957. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  50958. };
  50959. return LinesMesh;
  50960. }(BABYLON.Mesh));
  50961. BABYLON.LinesMesh = LinesMesh;
  50962. })(BABYLON || (BABYLON = {}));
  50963. //# sourceMappingURL=babylon.linesMesh.js.map
  50964. var BABYLON;
  50965. (function (BABYLON) {
  50966. var MeshBuilder = /** @class */ (function () {
  50967. function MeshBuilder() {
  50968. }
  50969. MeshBuilder.updateSideOrientation = function (orientation) {
  50970. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  50971. return BABYLON.Mesh.DOUBLESIDE;
  50972. }
  50973. if (orientation === undefined || orientation === null) {
  50974. return BABYLON.Mesh.FRONTSIDE;
  50975. }
  50976. return orientation;
  50977. };
  50978. /**
  50979. * Creates a box mesh.
  50980. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  50981. * The parameter `size` sets the size (float) of each box side (default 1).
  50982. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  50983. * 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).
  50984. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50986. * 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).
  50987. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50989. */
  50990. MeshBuilder.CreateBox = function (name, options, scene) {
  50991. if (scene === void 0) { scene = null; }
  50992. var box = new BABYLON.Mesh(name, scene);
  50993. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50994. box._originalBuilderSideOrientation = options.sideOrientation;
  50995. var vertexData = BABYLON.VertexData.CreateBox(options);
  50996. vertexData.applyToMesh(box, options.updatable);
  50997. return box;
  50998. };
  50999. /**
  51000. * Creates a sphere mesh.
  51001. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51002. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51003. * 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`).
  51004. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51005. * 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
  51006. * 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).
  51007. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51008. * 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).
  51009. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51011. */
  51012. MeshBuilder.CreateSphere = function (name, options, scene) {
  51013. var sphere = new BABYLON.Mesh(name, scene);
  51014. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51015. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51016. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51017. vertexData.applyToMesh(sphere, options.updatable);
  51018. return sphere;
  51019. };
  51020. /**
  51021. * Creates a plane polygonal mesh. By default, this is a disc.
  51022. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51023. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51024. * 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.
  51025. * 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
  51026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51027. * 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).
  51028. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51030. */
  51031. MeshBuilder.CreateDisc = function (name, options, scene) {
  51032. if (scene === void 0) { scene = null; }
  51033. var disc = new BABYLON.Mesh(name, scene);
  51034. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51035. disc._originalBuilderSideOrientation = options.sideOrientation;
  51036. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51037. vertexData.applyToMesh(disc, options.updatable);
  51038. return disc;
  51039. };
  51040. /**
  51041. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51042. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51043. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51044. * 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`).
  51045. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51046. * 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.
  51047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51048. * 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).
  51049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51051. */
  51052. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51053. var sphere = new BABYLON.Mesh(name, scene);
  51054. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51055. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51056. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51057. vertexData.applyToMesh(sphere, options.updatable);
  51058. return sphere;
  51059. };
  51060. ;
  51061. /**
  51062. * Creates a ribbon mesh.
  51063. * 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.
  51064. *
  51065. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51066. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51067. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51068. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  51069. * 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.
  51070. * 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.
  51071. * 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
  51072. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51073. * 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).
  51074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51075. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51076. * 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.
  51077. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  51078. * 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
  51079. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  51080. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  51081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51082. */
  51083. MeshBuilder.CreateRibbon = function (name, options, scene) {
  51084. if (scene === void 0) { scene = null; }
  51085. var pathArray = options.pathArray;
  51086. var closeArray = options.closeArray;
  51087. var closePath = options.closePath;
  51088. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51089. var instance = options.instance;
  51090. var updatable = options.updatable;
  51091. if (instance) {
  51092. // positionFunction : ribbon case
  51093. // only pathArray and sideOrientation parameters are taken into account for positions update
  51094. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  51095. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  51096. var positionFunction = function (positions) {
  51097. var minlg = pathArray[0].length;
  51098. var i = 0;
  51099. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  51100. for (var si = 1; si <= ns; si++) {
  51101. for (var p = 0; p < pathArray.length; p++) {
  51102. var path = pathArray[p];
  51103. var l = path.length;
  51104. minlg = (minlg < l) ? minlg : l;
  51105. var j = 0;
  51106. while (j < minlg) {
  51107. positions[i] = path[j].x;
  51108. positions[i + 1] = path[j].y;
  51109. positions[i + 2] = path[j].z;
  51110. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  51111. BABYLON.Tmp.Vector3[0].x = path[j].x;
  51112. }
  51113. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  51114. BABYLON.Tmp.Vector3[1].x = path[j].x;
  51115. }
  51116. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  51117. BABYLON.Tmp.Vector3[0].y = path[j].y;
  51118. }
  51119. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  51120. BABYLON.Tmp.Vector3[1].y = path[j].y;
  51121. }
  51122. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  51123. BABYLON.Tmp.Vector3[0].z = path[j].z;
  51124. }
  51125. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  51126. BABYLON.Tmp.Vector3[1].z = path[j].z;
  51127. }
  51128. j++;
  51129. i += 3;
  51130. }
  51131. if (instance._closePath) {
  51132. positions[i] = path[0].x;
  51133. positions[i + 1] = path[0].y;
  51134. positions[i + 2] = path[0].z;
  51135. i += 3;
  51136. }
  51137. }
  51138. }
  51139. };
  51140. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51141. positionFunction(positions);
  51142. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  51143. instance._boundingInfo.update(instance._worldMatrix);
  51144. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51145. if (options.colors) {
  51146. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51147. for (var c = 0; c < options.colors.length; c++) {
  51148. colors[c * 4] = options.colors[c].r;
  51149. colors[c * 4 + 1] = options.colors[c].g;
  51150. colors[c * 4 + 2] = options.colors[c].b;
  51151. colors[c * 4 + 3] = options.colors[c].a;
  51152. }
  51153. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  51154. }
  51155. if (options.uvs) {
  51156. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51157. for (var i = 0; i < options.uvs.length; i++) {
  51158. uvs[i * 2] = options.uvs[i].x;
  51159. uvs[i * 2 + 1] = options.uvs[i].y;
  51160. }
  51161. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  51162. }
  51163. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  51164. var indices = instance.getIndices();
  51165. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51166. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  51167. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  51168. if (instance._closePath) {
  51169. var indexFirst = 0;
  51170. var indexLast = 0;
  51171. for (var p = 0; p < pathArray.length; p++) {
  51172. indexFirst = instance._idx[p] * 3;
  51173. if (p + 1 < pathArray.length) {
  51174. indexLast = (instance._idx[p + 1] - 1) * 3;
  51175. }
  51176. else {
  51177. indexLast = normals.length - 3;
  51178. }
  51179. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51180. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51181. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51182. normals[indexLast] = normals[indexFirst];
  51183. normals[indexLast + 1] = normals[indexFirst + 1];
  51184. normals[indexLast + 2] = normals[indexFirst + 2];
  51185. }
  51186. }
  51187. if (!(instance.areNormalsFrozen)) {
  51188. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51189. }
  51190. }
  51191. return instance;
  51192. }
  51193. else {
  51194. var ribbon = new BABYLON.Mesh(name, scene);
  51195. ribbon._originalBuilderSideOrientation = sideOrientation;
  51196. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51197. if (closePath) {
  51198. ribbon._idx = vertexData._idx;
  51199. }
  51200. ribbon._closePath = closePath;
  51201. ribbon._closeArray = closeArray;
  51202. vertexData.applyToMesh(ribbon, updatable);
  51203. return ribbon;
  51204. }
  51205. };
  51206. /**
  51207. * Creates a cylinder or a cone mesh.
  51208. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51209. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51210. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51211. * 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.
  51212. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51213. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51214. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51215. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51216. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51217. * 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).
  51218. * 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
  51219. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51220. * 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
  51221. * 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.
  51222. * If `enclose` is false, a ring surface is one element.
  51223. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51224. * 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
  51225. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51226. * 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).
  51227. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51228. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51229. */
  51230. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51231. var cylinder = new BABYLON.Mesh(name, scene);
  51232. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51233. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51234. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51235. vertexData.applyToMesh(cylinder, options.updatable);
  51236. return cylinder;
  51237. };
  51238. /**
  51239. * Creates a torus mesh.
  51240. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51241. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51242. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51243. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51244. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51245. * 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).
  51246. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51248. */
  51249. MeshBuilder.CreateTorus = function (name, options, scene) {
  51250. var torus = new BABYLON.Mesh(name, scene);
  51251. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51252. torus._originalBuilderSideOrientation = options.sideOrientation;
  51253. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51254. vertexData.applyToMesh(torus, options.updatable);
  51255. return torus;
  51256. };
  51257. /**
  51258. * Creates a torus knot mesh.
  51259. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51260. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51261. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51262. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51263. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51265. * 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).
  51266. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51268. */
  51269. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51270. var torusKnot = new BABYLON.Mesh(name, scene);
  51271. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51272. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51273. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51274. vertexData.applyToMesh(torusKnot, options.updatable);
  51275. return torusKnot;
  51276. };
  51277. /**
  51278. * Creates a line system mesh.
  51279. * A line system is a pool of many lines gathered in a single mesh.
  51280. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51281. * 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.
  51282. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51283. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51284. * 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
  51285. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51286. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51287. * 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
  51288. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51290. */
  51291. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51292. var instance = options.instance;
  51293. var lines = options.lines;
  51294. var colors = options.colors;
  51295. if (instance) {
  51296. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51297. var vertexColor;
  51298. var lineColors;
  51299. if (colors) {
  51300. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51301. }
  51302. var i = 0;
  51303. var c = 0;
  51304. for (var l = 0; l < lines.length; l++) {
  51305. var points = lines[l];
  51306. for (var p = 0; p < points.length; p++) {
  51307. positions[i] = points[p].x;
  51308. positions[i + 1] = points[p].y;
  51309. positions[i + 2] = points[p].z;
  51310. if (colors && vertexColor) {
  51311. lineColors = colors[l];
  51312. vertexColor[c] = lineColors[p].r;
  51313. vertexColor[c + 1] = lineColors[p].g;
  51314. vertexColor[c + 2] = lineColors[p].b;
  51315. vertexColor[c + 3] = lineColors[p].a;
  51316. c += 4;
  51317. }
  51318. i += 3;
  51319. }
  51320. }
  51321. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51322. if (colors && vertexColor) {
  51323. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51324. }
  51325. return instance;
  51326. }
  51327. // line system creation
  51328. var useVertexColor = (colors) ? true : false;
  51329. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51330. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51331. vertexData.applyToMesh(lineSystem, options.updatable);
  51332. return lineSystem;
  51333. };
  51334. /**
  51335. * Creates a line mesh.
  51336. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51337. * 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.
  51338. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51339. * The parameter `points` is an array successive Vector3.
  51340. * 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
  51341. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51342. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51343. * When updating an instance, remember that only point positions can change, not the number of points.
  51344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51345. */
  51346. MeshBuilder.CreateLines = function (name, options, scene) {
  51347. if (scene === void 0) { scene = null; }
  51348. var colors = (options.colors) ? [options.colors] : null;
  51349. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51350. return lines;
  51351. };
  51352. /**
  51353. * Creates a dashed line mesh.
  51354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51355. * 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.
  51356. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51357. * The parameter `points` is an array successive Vector3.
  51358. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51359. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51360. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51361. * 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
  51362. * When updating an instance, remember that only point positions can change, not the number of points.
  51363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51364. */
  51365. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51366. if (scene === void 0) { scene = null; }
  51367. var points = options.points;
  51368. var instance = options.instance;
  51369. var gapSize = options.gapSize || 1;
  51370. var dashSize = options.dashSize || 3;
  51371. if (instance) {
  51372. var positionFunction = function (positions) {
  51373. var curvect = BABYLON.Vector3.Zero();
  51374. var nbSeg = positions.length / 6;
  51375. var lg = 0;
  51376. var nb = 0;
  51377. var shft = 0;
  51378. var dashshft = 0;
  51379. var curshft = 0;
  51380. var p = 0;
  51381. var i = 0;
  51382. var j = 0;
  51383. for (i = 0; i < points.length - 1; i++) {
  51384. points[i + 1].subtractToRef(points[i], curvect);
  51385. lg += curvect.length();
  51386. }
  51387. shft = lg / nbSeg;
  51388. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51389. for (i = 0; i < points.length - 1; i++) {
  51390. points[i + 1].subtractToRef(points[i], curvect);
  51391. nb = Math.floor(curvect.length() / shft);
  51392. curvect.normalize();
  51393. j = 0;
  51394. while (j < nb && p < positions.length) {
  51395. curshft = shft * j;
  51396. positions[p] = points[i].x + curshft * curvect.x;
  51397. positions[p + 1] = points[i].y + curshft * curvect.y;
  51398. positions[p + 2] = points[i].z + curshft * curvect.z;
  51399. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51400. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51401. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51402. p += 6;
  51403. j++;
  51404. }
  51405. }
  51406. while (p < positions.length) {
  51407. positions[p] = points[i].x;
  51408. positions[p + 1] = points[i].y;
  51409. positions[p + 2] = points[i].z;
  51410. p += 3;
  51411. }
  51412. };
  51413. instance.updateMeshPositions(positionFunction, false);
  51414. return instance;
  51415. }
  51416. // dashed lines creation
  51417. var dashedLines = new BABYLON.LinesMesh(name, scene);
  51418. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  51419. vertexData.applyToMesh(dashedLines, options.updatable);
  51420. dashedLines.dashSize = dashSize;
  51421. dashedLines.gapSize = gapSize;
  51422. return dashedLines;
  51423. };
  51424. /**
  51425. * Creates an extruded shape mesh.
  51426. * 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.
  51427. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  51428. *
  51429. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51430. * 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
  51431. * extruded along the Z axis.
  51432. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51433. * 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.
  51434. * The parameter `scale` (float, default 1) is the value to scale the shape.
  51435. * 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
  51436. * 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
  51437. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51439. * 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).
  51440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51441. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51443. */
  51444. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  51445. if (scene === void 0) { scene = null; }
  51446. var path = options.path;
  51447. var shape = options.shape;
  51448. var scale = options.scale || 1;
  51449. var rotation = options.rotation || 0;
  51450. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51451. var updatable = options.updatable;
  51452. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51453. var instance = options.instance || null;
  51454. var invertUV = options.invertUV || false;
  51455. 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);
  51456. };
  51457. /**
  51458. * Creates an custom extruded shape mesh.
  51459. * 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.
  51460. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  51461. *
  51462. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51463. * 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
  51464. * extruded along the Z axis.
  51465. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51466. * 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
  51467. * and the distance of this point from the begining of the path :
  51468. * ```javascript
  51469. * var rotationFunction = function(i, distance) {
  51470. * // do things
  51471. * return rotationValue; }
  51472. * ```
  51473. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  51474. * 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
  51475. * and the distance of this point from the begining of the path :
  51476. * ```javascript
  51477. * var scaleFunction = function(i, distance) {
  51478. * // do things
  51479. * return scaleValue;}
  51480. * ```
  51481. * It must returns a float value that will be the scale value applied to the shape on each path point.
  51482. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  51483. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  51484. * 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
  51485. * 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
  51486. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51488. * 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).
  51489. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51490. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51492. */
  51493. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  51494. var path = options.path;
  51495. var shape = options.shape;
  51496. var scaleFunction = options.scaleFunction || (function () { return 1; });
  51497. var rotationFunction = options.rotationFunction || (function () { return 0; });
  51498. var ribbonCloseArray = options.ribbonCloseArray || false;
  51499. var ribbonClosePath = options.ribbonClosePath || false;
  51500. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51501. var updatable = options.updatable;
  51502. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51503. var instance = options.instance;
  51504. var invertUV = options.invertUV || false;
  51505. 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);
  51506. };
  51507. /**
  51508. * Creates lathe mesh.
  51509. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  51510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  51511. *
  51512. * 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
  51513. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  51514. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  51515. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  51516. * 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.
  51517. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  51518. * 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
  51519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51520. * 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).
  51521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51522. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51524. */
  51525. MeshBuilder.CreateLathe = function (name, options, scene) {
  51526. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  51527. var closed = (options.closed === undefined) ? true : options.closed;
  51528. var shape = options.shape;
  51529. var radius = options.radius || 1;
  51530. var tessellation = options.tessellation || 64;
  51531. var updatable = options.updatable;
  51532. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51533. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51534. var pi2 = Math.PI * 2;
  51535. var paths = new Array();
  51536. var invertUV = options.invertUV || false;
  51537. var i = 0;
  51538. var p = 0;
  51539. var step = pi2 / tessellation * arc;
  51540. var rotated;
  51541. var path = new Array();
  51542. ;
  51543. for (i = 0; i <= tessellation; i++) {
  51544. var path = [];
  51545. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  51546. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  51547. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  51548. }
  51549. for (p = 0; p < shape.length; p++) {
  51550. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  51551. path.push(rotated);
  51552. }
  51553. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  51554. 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));
  51555. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  51556. }
  51557. paths.push(path);
  51558. }
  51559. // lathe ribbon
  51560. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51561. return lathe;
  51562. };
  51563. /**
  51564. * Creates a plane mesh.
  51565. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51566. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  51567. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  51568. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  51569. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51570. * 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).
  51571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51573. */
  51574. MeshBuilder.CreatePlane = function (name, options, scene) {
  51575. var plane = new BABYLON.Mesh(name, scene);
  51576. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51577. plane._originalBuilderSideOrientation = options.sideOrientation;
  51578. var vertexData = BABYLON.VertexData.CreatePlane(options);
  51579. vertexData.applyToMesh(plane, options.updatable);
  51580. if (options.sourcePlane) {
  51581. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  51582. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  51583. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  51584. plane.rotate(vectorProduct, product);
  51585. }
  51586. return plane;
  51587. };
  51588. /**
  51589. * Creates a ground mesh.
  51590. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51591. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  51592. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  51593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51594. */
  51595. MeshBuilder.CreateGround = function (name, options, scene) {
  51596. var ground = new BABYLON.GroundMesh(name, scene);
  51597. ground._setReady(false);
  51598. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  51599. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  51600. ground._width = options.width || 1;
  51601. ground._height = options.height || 1;
  51602. ground._maxX = ground._width / 2;
  51603. ground._maxZ = ground._height / 2;
  51604. ground._minX = -ground._maxX;
  51605. ground._minZ = -ground._maxZ;
  51606. var vertexData = BABYLON.VertexData.CreateGround(options);
  51607. vertexData.applyToMesh(ground, options.updatable);
  51608. ground._setReady(true);
  51609. return ground;
  51610. };
  51611. /**
  51612. * Creates a tiled ground mesh.
  51613. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  51614. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  51615. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  51616. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  51617. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  51618. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  51619. * numbers of subdivisions on the ground width and height of each tile.
  51620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51621. */
  51622. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  51623. var tiledGround = new BABYLON.Mesh(name, scene);
  51624. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  51625. vertexData.applyToMesh(tiledGround, options.updatable);
  51626. return tiledGround;
  51627. };
  51628. /**
  51629. * Creates a ground mesh from a height map.
  51630. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  51631. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  51632. * The parameter `url` sets the URL of the height map image resource.
  51633. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  51634. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  51635. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  51636. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  51637. * 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.
  51638. * 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).
  51639. * This function is passed the newly built mesh :
  51640. * ```javascript
  51641. * function(mesh) { // do things
  51642. * return; }
  51643. * ```
  51644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51645. */
  51646. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  51647. var width = options.width || 10.0;
  51648. var height = options.height || 10.0;
  51649. var subdivisions = options.subdivisions || 1 | 0;
  51650. var minHeight = options.minHeight || 0.0;
  51651. var maxHeight = options.maxHeight || 1.0;
  51652. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  51653. var updatable = options.updatable;
  51654. var onReady = options.onReady;
  51655. var ground = new BABYLON.GroundMesh(name, scene);
  51656. ground._subdivisionsX = subdivisions;
  51657. ground._subdivisionsY = subdivisions;
  51658. ground._width = width;
  51659. ground._height = height;
  51660. ground._maxX = ground._width / 2.0;
  51661. ground._maxZ = ground._height / 2.0;
  51662. ground._minX = -ground._maxX;
  51663. ground._minZ = -ground._maxZ;
  51664. ground._setReady(false);
  51665. var onload = function (img) {
  51666. // Getting height map data
  51667. var canvas = document.createElement("canvas");
  51668. var context = canvas.getContext("2d");
  51669. if (!context) {
  51670. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  51671. }
  51672. if (scene.isDisposed) {
  51673. return;
  51674. }
  51675. var bufferWidth = img.width;
  51676. var bufferHeight = img.height;
  51677. canvas.width = bufferWidth;
  51678. canvas.height = bufferHeight;
  51679. context.drawImage(img, 0, 0);
  51680. // Create VertexData from map data
  51681. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  51682. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  51683. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  51684. width: width, height: height,
  51685. subdivisions: subdivisions,
  51686. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  51687. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  51688. });
  51689. vertexData.applyToMesh(ground, updatable);
  51690. ground._setReady(true);
  51691. //execute ready callback, if set
  51692. if (onReady) {
  51693. onReady(ground);
  51694. }
  51695. };
  51696. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  51697. return ground;
  51698. };
  51699. /**
  51700. * Creates a polygon mesh.
  51701. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  51702. * 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.
  51703. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51705. * 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).
  51706. * Remember you can only change the shape positions, not their number when updating a polygon.
  51707. */
  51708. MeshBuilder.CreatePolygon = function (name, options, scene) {
  51709. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51710. var shape = options.shape;
  51711. var holes = options.holes || [];
  51712. var depth = options.depth || 0;
  51713. var contours = [];
  51714. var hole = [];
  51715. for (var i = 0; i < shape.length; i++) {
  51716. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  51717. }
  51718. var epsilon = 0.00000001;
  51719. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  51720. contours.pop();
  51721. }
  51722. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  51723. for (var hNb = 0; hNb < holes.length; hNb++) {
  51724. hole = [];
  51725. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  51726. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  51727. }
  51728. polygonTriangulation.addHole(hole);
  51729. }
  51730. var polygon = polygonTriangulation.build(options.updatable, depth);
  51731. polygon._originalBuilderSideOrientation = options.sideOrientation;
  51732. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  51733. vertexData.applyToMesh(polygon, options.updatable);
  51734. return polygon;
  51735. };
  51736. ;
  51737. /**
  51738. * Creates an extruded polygon mesh, with depth in the Y direction.
  51739. * 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).
  51740. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51741. */
  51742. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  51743. return MeshBuilder.CreatePolygon(name, options, scene);
  51744. };
  51745. ;
  51746. /**
  51747. * Creates a tube mesh.
  51748. * 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.
  51749. *
  51750. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  51751. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  51752. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  51753. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  51754. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  51755. * 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.
  51756. * It must return a radius value (positive float) :
  51757. * ```javascript
  51758. * var radiusFunction = function(i, distance) {
  51759. * // do things
  51760. * return radius; }
  51761. * ```
  51762. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  51763. * 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
  51764. * 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
  51765. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51766. * 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).
  51767. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51768. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51770. */
  51771. MeshBuilder.CreateTube = function (name, options, scene) {
  51772. var path = options.path;
  51773. var instance = options.instance;
  51774. var radius = 1.0;
  51775. if (instance) {
  51776. radius = instance.radius;
  51777. }
  51778. if (options.radius !== undefined) {
  51779. radius = options.radius;
  51780. }
  51781. ;
  51782. var tessellation = options.tessellation || 64 | 0;
  51783. var radiusFunction = options.radiusFunction || null;
  51784. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51785. var invertUV = options.invertUV || false;
  51786. var updatable = options.updatable;
  51787. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51788. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  51789. // tube geometry
  51790. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  51791. var tangents = path3D.getTangents();
  51792. var normals = path3D.getNormals();
  51793. var distances = path3D.getDistances();
  51794. var pi2 = Math.PI * 2;
  51795. var step = pi2 / tessellation * arc;
  51796. var returnRadius = function () { return radius; };
  51797. var radiusFunctionFinal = radiusFunction || returnRadius;
  51798. var circlePath;
  51799. var rad;
  51800. var normal;
  51801. var rotated;
  51802. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  51803. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  51804. for (var i = 0; i < path.length; i++) {
  51805. rad = radiusFunctionFinal(i, distances[i]); // current radius
  51806. circlePath = Array(); // current circle array
  51807. normal = normals[i]; // current normal
  51808. for (var t = 0; t < tessellation; t++) {
  51809. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  51810. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  51811. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  51812. rotated.scaleInPlace(rad).addInPlace(path[i]);
  51813. circlePath[t] = rotated;
  51814. }
  51815. circlePaths[index] = circlePath;
  51816. index++;
  51817. }
  51818. // cap
  51819. var capPath = function (nbPoints, pathIndex) {
  51820. var pointCap = Array();
  51821. for (var i = 0; i < nbPoints; i++) {
  51822. pointCap.push(path[pathIndex]);
  51823. }
  51824. return pointCap;
  51825. };
  51826. switch (cap) {
  51827. case BABYLON.Mesh.NO_CAP:
  51828. break;
  51829. case BABYLON.Mesh.CAP_START:
  51830. circlePaths[0] = capPath(tessellation, 0);
  51831. circlePaths[1] = circlePaths[2].slice(0);
  51832. break;
  51833. case BABYLON.Mesh.CAP_END:
  51834. circlePaths[index] = circlePaths[index - 1].slice(0);
  51835. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51836. break;
  51837. case BABYLON.Mesh.CAP_ALL:
  51838. circlePaths[0] = capPath(tessellation, 0);
  51839. circlePaths[1] = circlePaths[2].slice(0);
  51840. circlePaths[index] = circlePaths[index - 1].slice(0);
  51841. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51842. break;
  51843. default:
  51844. break;
  51845. }
  51846. return circlePaths;
  51847. };
  51848. var path3D;
  51849. var pathArray;
  51850. if (instance) {
  51851. var arc = options.arc || instance.arc;
  51852. path3D = (instance.path3D).update(path);
  51853. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  51854. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  51855. instance.path3D = path3D;
  51856. instance.pathArray = pathArray;
  51857. instance.arc = arc;
  51858. instance.radius = radius;
  51859. return instance;
  51860. }
  51861. // tube creation
  51862. path3D = new BABYLON.Path3D(path);
  51863. var newPathArray = new Array();
  51864. cap = (cap < 0 || cap > 3) ? 0 : cap;
  51865. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  51866. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51867. tube.pathArray = pathArray;
  51868. tube.path3D = path3D;
  51869. tube.tessellation = tessellation;
  51870. tube.cap = cap;
  51871. tube.arc = options.arc;
  51872. tube.radius = radius;
  51873. return tube;
  51874. };
  51875. /**
  51876. * Creates a polyhedron mesh.
  51877. *
  51878. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  51879. * 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
  51880. * to choose the wanted type.
  51881. * The parameter `size` (positive float, default 1) sets the polygon size.
  51882. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  51883. * 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`.
  51884. * 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
  51885. * 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)`).
  51886. * 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
  51887. * 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.
  51888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51889. * 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).
  51890. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51892. */
  51893. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  51894. var polyhedron = new BABYLON.Mesh(name, scene);
  51895. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51896. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  51897. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  51898. vertexData.applyToMesh(polyhedron, options.updatable);
  51899. return polyhedron;
  51900. };
  51901. /**
  51902. * Creates a decal mesh.
  51903. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  51904. * 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.
  51905. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  51906. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  51907. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  51908. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  51909. */
  51910. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  51911. var indices = sourceMesh.getIndices();
  51912. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51913. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51914. var position = options.position || BABYLON.Vector3.Zero();
  51915. var normal = options.normal || BABYLON.Vector3.Up();
  51916. var size = options.size || BABYLON.Vector3.One();
  51917. var angle = options.angle || 0;
  51918. // Getting correct rotation
  51919. if (!normal) {
  51920. var target = new BABYLON.Vector3(0, 0, 1);
  51921. var camera = sourceMesh.getScene().activeCamera;
  51922. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  51923. normal = camera.globalPosition.subtract(cameraWorldTarget);
  51924. }
  51925. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  51926. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  51927. var pitch = Math.atan2(normal.y, len);
  51928. // Matrix
  51929. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  51930. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  51931. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  51932. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  51933. var vertexData = new BABYLON.VertexData();
  51934. vertexData.indices = [];
  51935. vertexData.positions = [];
  51936. vertexData.normals = [];
  51937. vertexData.uvs = [];
  51938. var currentVertexDataIndex = 0;
  51939. var extractDecalVector3 = function (indexId) {
  51940. var result = new BABYLON.PositionNormalVertex();
  51941. if (!indices || !positions || !normals) {
  51942. return result;
  51943. }
  51944. var vertexId = indices[indexId];
  51945. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  51946. // Send vector to decal local world
  51947. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  51948. // Get normal
  51949. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  51950. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  51951. return result;
  51952. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  51953. var clip = function (vertices, axis) {
  51954. if (vertices.length === 0) {
  51955. return vertices;
  51956. }
  51957. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  51958. var clipVertices = function (v0, v1) {
  51959. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  51960. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  51961. };
  51962. var result = new Array();
  51963. for (var index = 0; index < vertices.length; index += 3) {
  51964. var v1Out;
  51965. var v2Out;
  51966. var v3Out;
  51967. var total = 0;
  51968. var nV1 = null;
  51969. var nV2 = null;
  51970. var nV3 = null;
  51971. var nV4 = null;
  51972. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  51973. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  51974. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  51975. v1Out = d1 > 0;
  51976. v2Out = d2 > 0;
  51977. v3Out = d3 > 0;
  51978. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  51979. switch (total) {
  51980. case 0:
  51981. result.push(vertices[index]);
  51982. result.push(vertices[index + 1]);
  51983. result.push(vertices[index + 2]);
  51984. break;
  51985. case 1:
  51986. if (v1Out) {
  51987. nV1 = vertices[index + 1];
  51988. nV2 = vertices[index + 2];
  51989. nV3 = clipVertices(vertices[index], nV1);
  51990. nV4 = clipVertices(vertices[index], nV2);
  51991. }
  51992. if (v2Out) {
  51993. nV1 = vertices[index];
  51994. nV2 = vertices[index + 2];
  51995. nV3 = clipVertices(vertices[index + 1], nV1);
  51996. nV4 = clipVertices(vertices[index + 1], nV2);
  51997. result.push(nV3);
  51998. result.push(nV2.clone());
  51999. result.push(nV1.clone());
  52000. result.push(nV2.clone());
  52001. result.push(nV3.clone());
  52002. result.push(nV4);
  52003. break;
  52004. }
  52005. if (v3Out) {
  52006. nV1 = vertices[index];
  52007. nV2 = vertices[index + 1];
  52008. nV3 = clipVertices(vertices[index + 2], nV1);
  52009. nV4 = clipVertices(vertices[index + 2], nV2);
  52010. }
  52011. if (nV1 && nV2 && nV3 && nV4) {
  52012. result.push(nV1.clone());
  52013. result.push(nV2.clone());
  52014. result.push(nV3);
  52015. result.push(nV4);
  52016. result.push(nV3.clone());
  52017. result.push(nV2.clone());
  52018. }
  52019. break;
  52020. case 2:
  52021. if (!v1Out) {
  52022. nV1 = vertices[index].clone();
  52023. nV2 = clipVertices(nV1, vertices[index + 1]);
  52024. nV3 = clipVertices(nV1, vertices[index + 2]);
  52025. result.push(nV1);
  52026. result.push(nV2);
  52027. result.push(nV3);
  52028. }
  52029. if (!v2Out) {
  52030. nV1 = vertices[index + 1].clone();
  52031. nV2 = clipVertices(nV1, vertices[index + 2]);
  52032. nV3 = clipVertices(nV1, vertices[index]);
  52033. result.push(nV1);
  52034. result.push(nV2);
  52035. result.push(nV3);
  52036. }
  52037. if (!v3Out) {
  52038. nV1 = vertices[index + 2].clone();
  52039. nV2 = clipVertices(nV1, vertices[index]);
  52040. nV3 = clipVertices(nV1, vertices[index + 1]);
  52041. result.push(nV1);
  52042. result.push(nV2);
  52043. result.push(nV3);
  52044. }
  52045. break;
  52046. case 3:
  52047. break;
  52048. }
  52049. }
  52050. return result;
  52051. };
  52052. for (var index = 0; index < indices.length; index += 3) {
  52053. var faceVertices = new Array();
  52054. faceVertices.push(extractDecalVector3(index));
  52055. faceVertices.push(extractDecalVector3(index + 1));
  52056. faceVertices.push(extractDecalVector3(index + 2));
  52057. // Clip
  52058. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52059. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52060. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52061. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52062. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52063. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52064. if (faceVertices.length === 0) {
  52065. continue;
  52066. }
  52067. // Add UVs and get back to world
  52068. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  52069. var vertex = faceVertices[vIndex];
  52070. //TODO check for Int32Array | Uint32Array | Uint16Array
  52071. vertexData.indices.push(currentVertexDataIndex);
  52072. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  52073. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  52074. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  52075. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  52076. currentVertexDataIndex++;
  52077. }
  52078. }
  52079. // Return mesh
  52080. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  52081. vertexData.applyToMesh(decal);
  52082. decal.position = position.clone();
  52083. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  52084. return decal;
  52085. };
  52086. // Privates
  52087. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  52088. // extrusion geometry
  52089. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  52090. var tangents = path3D.getTangents();
  52091. var normals = path3D.getNormals();
  52092. var binormals = path3D.getBinormals();
  52093. var distances = path3D.getDistances();
  52094. var angle = 0;
  52095. var returnScale = function () { return scale !== null ? scale : 1; };
  52096. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  52097. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  52098. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  52099. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52100. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52101. for (var i = 0; i < curve.length; i++) {
  52102. var shapePath = new Array();
  52103. var angleStep = rotate(i, distances[i]);
  52104. var scaleRatio = scl(i, distances[i]);
  52105. for (var p = 0; p < shape.length; p++) {
  52106. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  52107. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  52108. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  52109. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  52110. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  52111. shapePath[p] = rotated;
  52112. }
  52113. shapePaths[index] = shapePath;
  52114. angle += angleStep;
  52115. index++;
  52116. }
  52117. // cap
  52118. var capPath = function (shapePath) {
  52119. var pointCap = Array();
  52120. var barycenter = BABYLON.Vector3.Zero();
  52121. var i;
  52122. for (i = 0; i < shapePath.length; i++) {
  52123. barycenter.addInPlace(shapePath[i]);
  52124. }
  52125. barycenter.scaleInPlace(1.0 / shapePath.length);
  52126. for (i = 0; i < shapePath.length; i++) {
  52127. pointCap.push(barycenter);
  52128. }
  52129. return pointCap;
  52130. };
  52131. switch (cap) {
  52132. case BABYLON.Mesh.NO_CAP:
  52133. break;
  52134. case BABYLON.Mesh.CAP_START:
  52135. shapePaths[0] = capPath(shapePaths[2]);
  52136. shapePaths[1] = shapePaths[2];
  52137. break;
  52138. case BABYLON.Mesh.CAP_END:
  52139. shapePaths[index] = shapePaths[index - 1];
  52140. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52141. break;
  52142. case BABYLON.Mesh.CAP_ALL:
  52143. shapePaths[0] = capPath(shapePaths[2]);
  52144. shapePaths[1] = shapePaths[2];
  52145. shapePaths[index] = shapePaths[index - 1];
  52146. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52147. break;
  52148. default:
  52149. break;
  52150. }
  52151. return shapePaths;
  52152. };
  52153. var path3D;
  52154. var pathArray;
  52155. if (instance) {
  52156. path3D = (instance.path3D).update(curve);
  52157. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  52158. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  52159. return instance;
  52160. }
  52161. // extruded shape creation
  52162. path3D = new BABYLON.Path3D(curve);
  52163. var newShapePaths = new Array();
  52164. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52165. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  52166. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  52167. extrudedGeneric.pathArray = pathArray;
  52168. extrudedGeneric.path3D = path3D;
  52169. extrudedGeneric.cap = cap;
  52170. return extrudedGeneric;
  52171. };
  52172. return MeshBuilder;
  52173. }());
  52174. BABYLON.MeshBuilder = MeshBuilder;
  52175. })(BABYLON || (BABYLON = {}));
  52176. //# sourceMappingURL=babylon.meshBuilder.js.map
  52177. var BABYLON;
  52178. (function (BABYLON) {
  52179. var AudioEngine = /** @class */ (function () {
  52180. function AudioEngine() {
  52181. this._audioContext = null;
  52182. this._audioContextInitialized = false;
  52183. this.canUseWebAudio = false;
  52184. this.WarnedWebAudioUnsupported = false;
  52185. this.unlocked = false;
  52186. this.isMP3supported = false;
  52187. this.isOGGsupported = false;
  52188. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52189. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52190. this.canUseWebAudio = true;
  52191. }
  52192. var audioElem = document.createElement('audio');
  52193. try {
  52194. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52195. this.isMP3supported = true;
  52196. }
  52197. }
  52198. catch (e) {
  52199. // protect error during capability check.
  52200. }
  52201. try {
  52202. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52203. this.isOGGsupported = true;
  52204. }
  52205. }
  52206. catch (e) {
  52207. // protect error during capability check.
  52208. }
  52209. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52210. this._unlockiOSaudio();
  52211. }
  52212. else {
  52213. this.unlocked = true;
  52214. }
  52215. }
  52216. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52217. get: function () {
  52218. if (!this._audioContextInitialized) {
  52219. this._initializeAudioContext();
  52220. }
  52221. return this._audioContext;
  52222. },
  52223. enumerable: true,
  52224. configurable: true
  52225. });
  52226. AudioEngine.prototype._unlockiOSaudio = function () {
  52227. var _this = this;
  52228. var unlockaudio = function () {
  52229. if (!_this.audioContext) {
  52230. return;
  52231. }
  52232. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52233. var source = _this.audioContext.createBufferSource();
  52234. source.buffer = buffer;
  52235. source.connect(_this.audioContext.destination);
  52236. source.start(0);
  52237. setTimeout(function () {
  52238. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52239. _this.unlocked = true;
  52240. window.removeEventListener('touchend', unlockaudio, false);
  52241. if (_this.onAudioUnlocked) {
  52242. _this.onAudioUnlocked();
  52243. }
  52244. }
  52245. }, 0);
  52246. };
  52247. window.addEventListener('touchend', unlockaudio, false);
  52248. };
  52249. AudioEngine.prototype._initializeAudioContext = function () {
  52250. try {
  52251. if (this.canUseWebAudio) {
  52252. this._audioContext = new AudioContext();
  52253. // create a global volume gain node
  52254. this.masterGain = this._audioContext.createGain();
  52255. this.masterGain.gain.value = 1;
  52256. this.masterGain.connect(this._audioContext.destination);
  52257. this._audioContextInitialized = true;
  52258. }
  52259. }
  52260. catch (e) {
  52261. this.canUseWebAudio = false;
  52262. BABYLON.Tools.Error("Web Audio: " + e.message);
  52263. }
  52264. };
  52265. AudioEngine.prototype.dispose = function () {
  52266. if (this.canUseWebAudio && this._audioContextInitialized) {
  52267. if (this._connectedAnalyser && this._audioContext) {
  52268. this._connectedAnalyser.stopDebugCanvas();
  52269. this._connectedAnalyser.dispose();
  52270. this.masterGain.disconnect();
  52271. this.masterGain.connect(this._audioContext.destination);
  52272. this._connectedAnalyser = null;
  52273. }
  52274. this.masterGain.gain.value = 1;
  52275. }
  52276. this.WarnedWebAudioUnsupported = false;
  52277. };
  52278. AudioEngine.prototype.getGlobalVolume = function () {
  52279. if (this.canUseWebAudio && this._audioContextInitialized) {
  52280. return this.masterGain.gain.value;
  52281. }
  52282. else {
  52283. return -1;
  52284. }
  52285. };
  52286. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52287. if (this.canUseWebAudio && this._audioContextInitialized) {
  52288. this.masterGain.gain.value = newVolume;
  52289. }
  52290. };
  52291. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52292. if (this._connectedAnalyser) {
  52293. this._connectedAnalyser.stopDebugCanvas();
  52294. }
  52295. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52296. this._connectedAnalyser = analyser;
  52297. this.masterGain.disconnect();
  52298. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52299. }
  52300. };
  52301. return AudioEngine;
  52302. }());
  52303. BABYLON.AudioEngine = AudioEngine;
  52304. })(BABYLON || (BABYLON = {}));
  52305. //# sourceMappingURL=babylon.audioEngine.js.map
  52306. var BABYLON;
  52307. (function (BABYLON) {
  52308. var Sound = /** @class */ (function () {
  52309. /**
  52310. * Create a sound and attach it to a scene
  52311. * @param name Name of your sound
  52312. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52313. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52314. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52315. */
  52316. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52317. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52318. var _this = this;
  52319. this.autoplay = false;
  52320. this.loop = false;
  52321. this.useCustomAttenuation = false;
  52322. this.spatialSound = false;
  52323. this.refDistance = 1;
  52324. this.rolloffFactor = 1;
  52325. this.maxDistance = 100;
  52326. this.distanceModel = "linear";
  52327. this._panningModel = "equalpower";
  52328. this._playbackRate = 1;
  52329. this._streaming = false;
  52330. this._startTime = 0;
  52331. this._startOffset = 0;
  52332. this._position = BABYLON.Vector3.Zero();
  52333. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52334. this._volume = 1;
  52335. this._isReadyToPlay = false;
  52336. this.isPlaying = false;
  52337. this.isPaused = false;
  52338. this._isDirectional = false;
  52339. // Used if you'd like to create a directional sound.
  52340. // If not set, the sound will be omnidirectional
  52341. this._coneInnerAngle = 360;
  52342. this._coneOuterAngle = 360;
  52343. this._coneOuterGain = 0;
  52344. this._isOutputConnected = false;
  52345. this._urlType = "Unknown";
  52346. this.name = name;
  52347. this._scene = scene;
  52348. this._readyToPlayCallback = readyToPlayCallback;
  52349. // Default custom attenuation function is a linear attenuation
  52350. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52351. if (currentDistance < maxDistance) {
  52352. return currentVolume * (1 - currentDistance / maxDistance);
  52353. }
  52354. else {
  52355. return 0;
  52356. }
  52357. };
  52358. if (options) {
  52359. this.autoplay = options.autoplay || false;
  52360. this.loop = options.loop || false;
  52361. // if volume === 0, we need another way to check this option
  52362. if (options.volume !== undefined) {
  52363. this._volume = options.volume;
  52364. }
  52365. this.spatialSound = options.spatialSound || false;
  52366. this.maxDistance = options.maxDistance || 100;
  52367. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52368. this.rolloffFactor = options.rolloffFactor || 1;
  52369. this.refDistance = options.refDistance || 1;
  52370. this.distanceModel = options.distanceModel || "linear";
  52371. this._playbackRate = options.playbackRate || 1;
  52372. this._streaming = options.streaming || false;
  52373. }
  52374. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52375. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52376. this._soundGain.gain.value = this._volume;
  52377. this._inputAudioNode = this._soundGain;
  52378. this._ouputAudioNode = this._soundGain;
  52379. if (this.spatialSound) {
  52380. this._createSpatialParameters();
  52381. }
  52382. this._scene.mainSoundTrack.AddSound(this);
  52383. var validParameter = true;
  52384. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52385. if (urlOrArrayBuffer) {
  52386. if (typeof (urlOrArrayBuffer) === "string")
  52387. this._urlType = "String";
  52388. if (Array.isArray(urlOrArrayBuffer))
  52389. this._urlType = "Array";
  52390. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52391. this._urlType = "ArrayBuffer";
  52392. var urls = [];
  52393. var codecSupportedFound = false;
  52394. switch (this._urlType) {
  52395. case "ArrayBuffer":
  52396. if (urlOrArrayBuffer.byteLength > 0) {
  52397. codecSupportedFound = true;
  52398. this._soundLoaded(urlOrArrayBuffer);
  52399. }
  52400. break;
  52401. case "String":
  52402. urls.push(urlOrArrayBuffer);
  52403. case "Array":
  52404. if (urls.length === 0)
  52405. urls = urlOrArrayBuffer;
  52406. // If we found a supported format, we load it immediately and stop the loop
  52407. for (var i = 0; i < urls.length; i++) {
  52408. var url = urls[i];
  52409. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  52410. codecSupportedFound = true;
  52411. }
  52412. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  52413. codecSupportedFound = true;
  52414. }
  52415. if (url.indexOf(".wav", url.length - 4) !== -1) {
  52416. codecSupportedFound = true;
  52417. }
  52418. if (url.indexOf("blob:") !== -1) {
  52419. codecSupportedFound = true;
  52420. }
  52421. if (codecSupportedFound) {
  52422. // Loading sound using XHR2
  52423. if (!this._streaming) {
  52424. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  52425. }
  52426. else {
  52427. this._htmlAudioElement = new Audio(url);
  52428. this._htmlAudioElement.controls = false;
  52429. this._htmlAudioElement.loop = this.loop;
  52430. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  52431. this._htmlAudioElement.preload = "auto";
  52432. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  52433. _this._isReadyToPlay = true;
  52434. if (_this.autoplay) {
  52435. _this.play();
  52436. }
  52437. if (_this._readyToPlayCallback) {
  52438. _this._readyToPlayCallback();
  52439. }
  52440. });
  52441. document.body.appendChild(this._htmlAudioElement);
  52442. }
  52443. break;
  52444. }
  52445. }
  52446. break;
  52447. default:
  52448. validParameter = false;
  52449. break;
  52450. }
  52451. if (!validParameter) {
  52452. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  52453. }
  52454. else {
  52455. if (!codecSupportedFound) {
  52456. this._isReadyToPlay = true;
  52457. // Simulating a ready to play event to avoid breaking code path
  52458. if (this._readyToPlayCallback) {
  52459. window.setTimeout(function () {
  52460. if (_this._readyToPlayCallback) {
  52461. _this._readyToPlayCallback();
  52462. }
  52463. }, 1000);
  52464. }
  52465. }
  52466. }
  52467. }
  52468. }
  52469. else {
  52470. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  52471. this._scene.mainSoundTrack.AddSound(this);
  52472. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  52473. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  52474. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  52475. }
  52476. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  52477. if (this._readyToPlayCallback) {
  52478. window.setTimeout(function () {
  52479. if (_this._readyToPlayCallback) {
  52480. _this._readyToPlayCallback();
  52481. }
  52482. }, 1000);
  52483. }
  52484. }
  52485. }
  52486. Sound.prototype.dispose = function () {
  52487. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  52488. if (this.isPlaying) {
  52489. this.stop();
  52490. }
  52491. this._isReadyToPlay = false;
  52492. if (this.soundTrackId === -1) {
  52493. this._scene.mainSoundTrack.RemoveSound(this);
  52494. }
  52495. else {
  52496. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  52497. }
  52498. if (this._soundGain) {
  52499. this._soundGain.disconnect();
  52500. this._soundGain = null;
  52501. }
  52502. if (this._soundPanner) {
  52503. this._soundPanner.disconnect();
  52504. this._soundPanner = null;
  52505. }
  52506. if (this._soundSource) {
  52507. this._soundSource.disconnect();
  52508. this._soundSource = null;
  52509. }
  52510. this._audioBuffer = null;
  52511. if (this._htmlAudioElement) {
  52512. this._htmlAudioElement.pause();
  52513. this._htmlAudioElement.src = "";
  52514. document.body.removeChild(this._htmlAudioElement);
  52515. }
  52516. if (this._connectedMesh && this._registerFunc) {
  52517. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52518. this._connectedMesh = null;
  52519. }
  52520. }
  52521. };
  52522. Sound.prototype.isReady = function () {
  52523. return this._isReadyToPlay;
  52524. };
  52525. Sound.prototype._soundLoaded = function (audioData) {
  52526. var _this = this;
  52527. if (!BABYLON.Engine.audioEngine.audioContext) {
  52528. return;
  52529. }
  52530. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  52531. _this._audioBuffer = buffer;
  52532. _this._isReadyToPlay = true;
  52533. if (_this.autoplay) {
  52534. _this.play();
  52535. }
  52536. if (_this._readyToPlayCallback) {
  52537. _this._readyToPlayCallback();
  52538. }
  52539. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  52540. };
  52541. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  52542. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52543. this._audioBuffer = audioBuffer;
  52544. this._isReadyToPlay = true;
  52545. }
  52546. };
  52547. Sound.prototype.updateOptions = function (options) {
  52548. if (options) {
  52549. this.loop = options.loop || this.loop;
  52550. this.maxDistance = options.maxDistance || this.maxDistance;
  52551. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  52552. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  52553. this.refDistance = options.refDistance || this.refDistance;
  52554. this.distanceModel = options.distanceModel || this.distanceModel;
  52555. this._playbackRate = options.playbackRate || this._playbackRate;
  52556. this._updateSpatialParameters();
  52557. if (this.isPlaying) {
  52558. if (this._streaming) {
  52559. this._htmlAudioElement.playbackRate = this._playbackRate;
  52560. }
  52561. else {
  52562. if (this._soundSource) {
  52563. this._soundSource.playbackRate.value = this._playbackRate;
  52564. }
  52565. }
  52566. }
  52567. }
  52568. };
  52569. Sound.prototype._createSpatialParameters = function () {
  52570. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52571. if (this._scene.headphone) {
  52572. this._panningModel = "HRTF";
  52573. }
  52574. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  52575. this._updateSpatialParameters();
  52576. this._soundPanner.connect(this._ouputAudioNode);
  52577. this._inputAudioNode = this._soundPanner;
  52578. }
  52579. };
  52580. Sound.prototype._updateSpatialParameters = function () {
  52581. if (this.spatialSound && this._soundPanner) {
  52582. if (this.useCustomAttenuation) {
  52583. // Tricks to disable in a way embedded Web Audio attenuation
  52584. this._soundPanner.distanceModel = "linear";
  52585. this._soundPanner.maxDistance = Number.MAX_VALUE;
  52586. this._soundPanner.refDistance = 1;
  52587. this._soundPanner.rolloffFactor = 1;
  52588. this._soundPanner.panningModel = this._panningModel;
  52589. }
  52590. else {
  52591. this._soundPanner.distanceModel = this.distanceModel;
  52592. this._soundPanner.maxDistance = this.maxDistance;
  52593. this._soundPanner.refDistance = this.refDistance;
  52594. this._soundPanner.rolloffFactor = this.rolloffFactor;
  52595. this._soundPanner.panningModel = this._panningModel;
  52596. }
  52597. }
  52598. };
  52599. Sound.prototype.switchPanningModelToHRTF = function () {
  52600. this._panningModel = "HRTF";
  52601. this._switchPanningModel();
  52602. };
  52603. Sound.prototype.switchPanningModelToEqualPower = function () {
  52604. this._panningModel = "equalpower";
  52605. this._switchPanningModel();
  52606. };
  52607. Sound.prototype._switchPanningModel = function () {
  52608. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52609. this._soundPanner.panningModel = this._panningModel;
  52610. }
  52611. };
  52612. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  52613. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52614. if (this._isOutputConnected) {
  52615. this._ouputAudioNode.disconnect();
  52616. }
  52617. this._ouputAudioNode.connect(soundTrackAudioNode);
  52618. this._isOutputConnected = true;
  52619. }
  52620. };
  52621. /**
  52622. * Transform this sound into a directional source
  52623. * @param coneInnerAngle Size of the inner cone in degree
  52624. * @param coneOuterAngle Size of the outer cone in degree
  52625. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  52626. */
  52627. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  52628. if (coneOuterAngle < coneInnerAngle) {
  52629. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  52630. return;
  52631. }
  52632. this._coneInnerAngle = coneInnerAngle;
  52633. this._coneOuterAngle = coneOuterAngle;
  52634. this._coneOuterGain = coneOuterGain;
  52635. this._isDirectional = true;
  52636. if (this.isPlaying && this.loop) {
  52637. this.stop();
  52638. this.play();
  52639. }
  52640. };
  52641. Sound.prototype.setPosition = function (newPosition) {
  52642. this._position = newPosition;
  52643. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52644. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52645. }
  52646. };
  52647. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  52648. this._localDirection = newLocalDirection;
  52649. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  52650. this._updateDirection();
  52651. }
  52652. };
  52653. Sound.prototype._updateDirection = function () {
  52654. if (!this._connectedMesh || !this._soundPanner) {
  52655. return;
  52656. }
  52657. var mat = this._connectedMesh.getWorldMatrix();
  52658. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  52659. direction.normalize();
  52660. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  52661. };
  52662. Sound.prototype.updateDistanceFromListener = function () {
  52663. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  52664. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  52665. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  52666. }
  52667. };
  52668. Sound.prototype.setAttenuationFunction = function (callback) {
  52669. this._customAttenuationFunction = callback;
  52670. };
  52671. /**
  52672. * Play the sound
  52673. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  52674. * @param offset (optional) Start the sound setting it at a specific time
  52675. */
  52676. Sound.prototype.play = function (time, offset) {
  52677. var _this = this;
  52678. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  52679. try {
  52680. if (this._startOffset < 0) {
  52681. time = -this._startOffset;
  52682. this._startOffset = 0;
  52683. }
  52684. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52685. if (!this._soundSource || !this._streamingSource) {
  52686. if (this.spatialSound && this._soundPanner) {
  52687. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52688. if (this._isDirectional) {
  52689. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  52690. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  52691. this._soundPanner.coneOuterGain = this._coneOuterGain;
  52692. if (this._connectedMesh) {
  52693. this._updateDirection();
  52694. }
  52695. else {
  52696. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  52697. }
  52698. }
  52699. }
  52700. }
  52701. if (this._streaming) {
  52702. if (!this._streamingSource) {
  52703. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  52704. this._htmlAudioElement.onended = function () { _this._onended(); };
  52705. this._htmlAudioElement.playbackRate = this._playbackRate;
  52706. }
  52707. this._streamingSource.disconnect();
  52708. this._streamingSource.connect(this._inputAudioNode);
  52709. this._htmlAudioElement.play();
  52710. }
  52711. else {
  52712. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  52713. this._soundSource.buffer = this._audioBuffer;
  52714. this._soundSource.connect(this._inputAudioNode);
  52715. this._soundSource.loop = this.loop;
  52716. this._soundSource.playbackRate.value = this._playbackRate;
  52717. this._soundSource.onended = function () { _this._onended(); };
  52718. if (this._soundSource.buffer) {
  52719. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  52720. }
  52721. }
  52722. this._startTime = startTime;
  52723. this.isPlaying = true;
  52724. this.isPaused = false;
  52725. }
  52726. catch (ex) {
  52727. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  52728. }
  52729. }
  52730. };
  52731. Sound.prototype._onended = function () {
  52732. this.isPlaying = false;
  52733. if (this.onended) {
  52734. this.onended();
  52735. }
  52736. };
  52737. /**
  52738. * Stop the sound
  52739. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  52740. */
  52741. Sound.prototype.stop = function (time) {
  52742. if (this.isPlaying) {
  52743. if (this._streaming) {
  52744. this._htmlAudioElement.pause();
  52745. // Test needed for Firefox or it will generate an Invalid State Error
  52746. if (this._htmlAudioElement.currentTime > 0) {
  52747. this._htmlAudioElement.currentTime = 0;
  52748. }
  52749. }
  52750. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  52751. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52752. this._soundSource.stop(stopTime);
  52753. this._soundSource.onended = function () { };
  52754. if (!this.isPaused) {
  52755. this._startOffset = 0;
  52756. }
  52757. }
  52758. this.isPlaying = false;
  52759. }
  52760. };
  52761. Sound.prototype.pause = function () {
  52762. if (this.isPlaying) {
  52763. this.isPaused = true;
  52764. if (this._streaming) {
  52765. this._htmlAudioElement.pause();
  52766. }
  52767. else if (BABYLON.Engine.audioEngine.audioContext) {
  52768. this.stop(0);
  52769. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  52770. }
  52771. }
  52772. };
  52773. Sound.prototype.setVolume = function (newVolume, time) {
  52774. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  52775. if (time && BABYLON.Engine.audioEngine.audioContext) {
  52776. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  52777. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  52778. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  52779. }
  52780. else {
  52781. this._soundGain.gain.value = newVolume;
  52782. }
  52783. }
  52784. this._volume = newVolume;
  52785. };
  52786. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  52787. this._playbackRate = newPlaybackRate;
  52788. if (this.isPlaying) {
  52789. if (this._streaming) {
  52790. this._htmlAudioElement.playbackRate = this._playbackRate;
  52791. }
  52792. else if (this._soundSource) {
  52793. this._soundSource.playbackRate.value = this._playbackRate;
  52794. }
  52795. }
  52796. };
  52797. Sound.prototype.getVolume = function () {
  52798. return this._volume;
  52799. };
  52800. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  52801. var _this = this;
  52802. if (this._connectedMesh && this._registerFunc) {
  52803. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52804. this._registerFunc = null;
  52805. }
  52806. this._connectedMesh = meshToConnectTo;
  52807. if (!this.spatialSound) {
  52808. this.spatialSound = true;
  52809. this._createSpatialParameters();
  52810. if (this.isPlaying && this.loop) {
  52811. this.stop();
  52812. this.play();
  52813. }
  52814. }
  52815. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  52816. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  52817. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  52818. };
  52819. Sound.prototype.detachFromMesh = function () {
  52820. if (this._connectedMesh && this._registerFunc) {
  52821. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52822. this._registerFunc = null;
  52823. this._connectedMesh = null;
  52824. }
  52825. };
  52826. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  52827. if (!node.getBoundingInfo) {
  52828. return;
  52829. }
  52830. var mesh = node;
  52831. var boundingInfo = mesh.getBoundingInfo();
  52832. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  52833. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  52834. this._updateDirection();
  52835. }
  52836. };
  52837. Sound.prototype.clone = function () {
  52838. var _this = this;
  52839. if (!this._streaming) {
  52840. var setBufferAndRun = function () {
  52841. if (_this._isReadyToPlay) {
  52842. clonedSound._audioBuffer = _this.getAudioBuffer();
  52843. clonedSound._isReadyToPlay = true;
  52844. if (clonedSound.autoplay) {
  52845. clonedSound.play();
  52846. }
  52847. }
  52848. else {
  52849. window.setTimeout(setBufferAndRun, 300);
  52850. }
  52851. };
  52852. var currentOptions = {
  52853. autoplay: this.autoplay, loop: this.loop,
  52854. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  52855. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  52856. refDistance: this.refDistance, distanceModel: this.distanceModel
  52857. };
  52858. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  52859. if (this.useCustomAttenuation) {
  52860. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  52861. }
  52862. clonedSound.setPosition(this._position);
  52863. clonedSound.setPlaybackRate(this._playbackRate);
  52864. setBufferAndRun();
  52865. return clonedSound;
  52866. }
  52867. else {
  52868. return null;
  52869. }
  52870. };
  52871. Sound.prototype.getAudioBuffer = function () {
  52872. return this._audioBuffer;
  52873. };
  52874. Sound.prototype.serialize = function () {
  52875. var serializationObject = {
  52876. name: this.name,
  52877. url: this.name,
  52878. autoplay: this.autoplay,
  52879. loop: this.loop,
  52880. volume: this._volume,
  52881. spatialSound: this.spatialSound,
  52882. maxDistance: this.maxDistance,
  52883. rolloffFactor: this.rolloffFactor,
  52884. refDistance: this.refDistance,
  52885. distanceModel: this.distanceModel,
  52886. playbackRate: this._playbackRate,
  52887. panningModel: this._panningModel,
  52888. soundTrackId: this.soundTrackId
  52889. };
  52890. if (this.spatialSound) {
  52891. if (this._connectedMesh)
  52892. serializationObject.connectedMeshId = this._connectedMesh.id;
  52893. serializationObject.position = this._position.asArray();
  52894. serializationObject.refDistance = this.refDistance;
  52895. serializationObject.distanceModel = this.distanceModel;
  52896. serializationObject.isDirectional = this._isDirectional;
  52897. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  52898. serializationObject.coneInnerAngle = this._coneInnerAngle;
  52899. serializationObject.coneOuterAngle = this._coneOuterAngle;
  52900. serializationObject.coneOuterGain = this._coneOuterGain;
  52901. }
  52902. return serializationObject;
  52903. };
  52904. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  52905. var soundName = parsedSound.name;
  52906. var soundUrl;
  52907. if (parsedSound.url) {
  52908. soundUrl = rootUrl + parsedSound.url;
  52909. }
  52910. else {
  52911. soundUrl = rootUrl + soundName;
  52912. }
  52913. var options = {
  52914. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  52915. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  52916. rolloffFactor: parsedSound.rolloffFactor,
  52917. refDistance: parsedSound.refDistance,
  52918. distanceModel: parsedSound.distanceModel,
  52919. playbackRate: parsedSound.playbackRate
  52920. };
  52921. var newSound;
  52922. if (!sourceSound) {
  52923. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  52924. scene._addPendingData(newSound);
  52925. }
  52926. else {
  52927. var setBufferAndRun = function () {
  52928. if (sourceSound._isReadyToPlay) {
  52929. newSound._audioBuffer = sourceSound.getAudioBuffer();
  52930. newSound._isReadyToPlay = true;
  52931. if (newSound.autoplay) {
  52932. newSound.play();
  52933. }
  52934. }
  52935. else {
  52936. window.setTimeout(setBufferAndRun, 300);
  52937. }
  52938. };
  52939. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  52940. setBufferAndRun();
  52941. }
  52942. if (parsedSound.position) {
  52943. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  52944. newSound.setPosition(soundPosition);
  52945. }
  52946. if (parsedSound.isDirectional) {
  52947. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  52948. if (parsedSound.localDirectionToMesh) {
  52949. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  52950. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  52951. }
  52952. }
  52953. if (parsedSound.connectedMeshId) {
  52954. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  52955. if (connectedMesh) {
  52956. newSound.attachToMesh(connectedMesh);
  52957. }
  52958. }
  52959. return newSound;
  52960. };
  52961. return Sound;
  52962. }());
  52963. BABYLON.Sound = Sound;
  52964. })(BABYLON || (BABYLON = {}));
  52965. //# sourceMappingURL=babylon.sound.js.map
  52966. var BABYLON;
  52967. (function (BABYLON) {
  52968. var SoundTrack = /** @class */ (function () {
  52969. function SoundTrack(scene, options) {
  52970. this.id = -1;
  52971. this._isMainTrack = false;
  52972. this._isInitialized = false;
  52973. this._scene = scene;
  52974. this.soundCollection = new Array();
  52975. this._options = options;
  52976. if (!this._isMainTrack) {
  52977. this._scene.soundTracks.push(this);
  52978. this.id = this._scene.soundTracks.length - 1;
  52979. }
  52980. }
  52981. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  52982. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52983. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  52984. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  52985. if (this._options) {
  52986. if (this._options.volume) {
  52987. this._outputAudioNode.gain.value = this._options.volume;
  52988. }
  52989. if (this._options.mainTrack) {
  52990. this._isMainTrack = this._options.mainTrack;
  52991. }
  52992. }
  52993. this._isInitialized = true;
  52994. }
  52995. };
  52996. SoundTrack.prototype.dispose = function () {
  52997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52998. if (this._connectedAnalyser) {
  52999. this._connectedAnalyser.stopDebugCanvas();
  53000. }
  53001. while (this.soundCollection.length) {
  53002. this.soundCollection[0].dispose();
  53003. }
  53004. if (this._outputAudioNode) {
  53005. this._outputAudioNode.disconnect();
  53006. }
  53007. this._outputAudioNode = null;
  53008. }
  53009. };
  53010. SoundTrack.prototype.AddSound = function (sound) {
  53011. if (!this._isInitialized) {
  53012. this._initializeSoundTrackAudioGraph();
  53013. }
  53014. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53015. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53016. }
  53017. if (sound.soundTrackId) {
  53018. if (sound.soundTrackId === -1) {
  53019. this._scene.mainSoundTrack.RemoveSound(sound);
  53020. }
  53021. else {
  53022. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53023. }
  53024. }
  53025. this.soundCollection.push(sound);
  53026. sound.soundTrackId = this.id;
  53027. };
  53028. SoundTrack.prototype.RemoveSound = function (sound) {
  53029. var index = this.soundCollection.indexOf(sound);
  53030. if (index !== -1) {
  53031. this.soundCollection.splice(index, 1);
  53032. }
  53033. };
  53034. SoundTrack.prototype.setVolume = function (newVolume) {
  53035. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53036. this._outputAudioNode.gain.value = newVolume;
  53037. }
  53038. };
  53039. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53040. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53041. for (var i = 0; i < this.soundCollection.length; i++) {
  53042. this.soundCollection[i].switchPanningModelToHRTF();
  53043. }
  53044. }
  53045. };
  53046. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53047. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53048. for (var i = 0; i < this.soundCollection.length; i++) {
  53049. this.soundCollection[i].switchPanningModelToEqualPower();
  53050. }
  53051. }
  53052. };
  53053. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53054. if (this._connectedAnalyser) {
  53055. this._connectedAnalyser.stopDebugCanvas();
  53056. }
  53057. this._connectedAnalyser = analyser;
  53058. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53059. this._outputAudioNode.disconnect();
  53060. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53061. }
  53062. };
  53063. return SoundTrack;
  53064. }());
  53065. BABYLON.SoundTrack = SoundTrack;
  53066. })(BABYLON || (BABYLON = {}));
  53067. //# sourceMappingURL=babylon.soundtrack.js.map
  53068. var BABYLON;
  53069. (function (BABYLON) {
  53070. var Analyser = /** @class */ (function () {
  53071. function Analyser(scene) {
  53072. this.SMOOTHING = 0.75;
  53073. this.FFT_SIZE = 512;
  53074. this.BARGRAPHAMPLITUDE = 256;
  53075. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53076. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53077. this._scene = scene;
  53078. this._audioEngine = BABYLON.Engine.audioEngine;
  53079. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  53080. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53081. this._webAudioAnalyser.minDecibels = -140;
  53082. this._webAudioAnalyser.maxDecibels = 0;
  53083. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53084. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53085. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53086. }
  53087. }
  53088. Analyser.prototype.getFrequencyBinCount = function () {
  53089. if (this._audioEngine.canUseWebAudio) {
  53090. return this._webAudioAnalyser.frequencyBinCount;
  53091. }
  53092. else {
  53093. return 0;
  53094. }
  53095. };
  53096. Analyser.prototype.getByteFrequencyData = function () {
  53097. if (this._audioEngine.canUseWebAudio) {
  53098. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53099. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53100. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53101. }
  53102. return this._byteFreqs;
  53103. };
  53104. Analyser.prototype.getByteTimeDomainData = function () {
  53105. if (this._audioEngine.canUseWebAudio) {
  53106. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53107. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53108. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53109. }
  53110. return this._byteTime;
  53111. };
  53112. Analyser.prototype.getFloatFrequencyData = function () {
  53113. if (this._audioEngine.canUseWebAudio) {
  53114. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53115. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53116. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53117. }
  53118. return this._floatFreqs;
  53119. };
  53120. Analyser.prototype.drawDebugCanvas = function () {
  53121. var _this = this;
  53122. if (this._audioEngine.canUseWebAudio) {
  53123. if (!this._debugCanvas) {
  53124. this._debugCanvas = document.createElement("canvas");
  53125. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53126. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53127. this._debugCanvas.style.position = "absolute";
  53128. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53129. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53130. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53131. document.body.appendChild(this._debugCanvas);
  53132. this._registerFunc = function () {
  53133. _this.drawDebugCanvas();
  53134. };
  53135. this._scene.registerBeforeRender(this._registerFunc);
  53136. }
  53137. if (this._registerFunc && this._debugCanvasContext) {
  53138. var workingArray = this.getByteFrequencyData();
  53139. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53140. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53141. // Draw the frequency domain chart.
  53142. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53143. var value = workingArray[i];
  53144. var percent = value / this.BARGRAPHAMPLITUDE;
  53145. var height = this.DEBUGCANVASSIZE.height * percent;
  53146. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53147. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53148. var hue = i / this.getFrequencyBinCount() * 360;
  53149. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53150. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53151. }
  53152. }
  53153. }
  53154. };
  53155. Analyser.prototype.stopDebugCanvas = function () {
  53156. if (this._debugCanvas) {
  53157. if (this._registerFunc) {
  53158. this._scene.unregisterBeforeRender(this._registerFunc);
  53159. this._registerFunc = null;
  53160. }
  53161. document.body.removeChild(this._debugCanvas);
  53162. this._debugCanvas = null;
  53163. this._debugCanvasContext = null;
  53164. }
  53165. };
  53166. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53167. if (this._audioEngine.canUseWebAudio) {
  53168. inputAudioNode.connect(this._webAudioAnalyser);
  53169. this._webAudioAnalyser.connect(outputAudioNode);
  53170. }
  53171. };
  53172. Analyser.prototype.dispose = function () {
  53173. if (this._audioEngine.canUseWebAudio) {
  53174. this._webAudioAnalyser.disconnect();
  53175. }
  53176. };
  53177. return Analyser;
  53178. }());
  53179. BABYLON.Analyser = Analyser;
  53180. })(BABYLON || (BABYLON = {}));
  53181. //# sourceMappingURL=babylon.analyser.js.map
  53182. var BABYLON;
  53183. (function (BABYLON) {
  53184. var CubeTexture = /** @class */ (function (_super) {
  53185. __extends(CubeTexture, _super);
  53186. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53187. if (extensions === void 0) { extensions = null; }
  53188. if (noMipmap === void 0) { noMipmap = false; }
  53189. if (files === void 0) { files = null; }
  53190. if (onLoad === void 0) { onLoad = null; }
  53191. if (onError === void 0) { onError = null; }
  53192. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53193. if (prefiltered === void 0) { prefiltered = false; }
  53194. if (forcedExtension === void 0) { forcedExtension = null; }
  53195. var _this = _super.call(this, scene) || this;
  53196. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53197. _this.name = rootUrl;
  53198. _this.url = rootUrl;
  53199. _this._noMipmap = noMipmap;
  53200. _this.hasAlpha = false;
  53201. _this._format = format;
  53202. _this._prefiltered = prefiltered;
  53203. _this.isCube = true;
  53204. _this._textureMatrix = BABYLON.Matrix.Identity();
  53205. if (prefiltered) {
  53206. _this.gammaSpace = false;
  53207. }
  53208. if (!rootUrl && !files) {
  53209. return _this;
  53210. }
  53211. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53212. var lastDot = rootUrl.lastIndexOf(".");
  53213. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53214. var isDDS = (extension === ".dds");
  53215. if (!files) {
  53216. if (!isDDS && !extensions) {
  53217. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53218. }
  53219. files = [];
  53220. if (extensions) {
  53221. for (var index = 0; index < extensions.length; index++) {
  53222. files.push(rootUrl + extensions[index]);
  53223. }
  53224. }
  53225. }
  53226. _this._files = files;
  53227. if (!_this._texture) {
  53228. if (!scene.useDelayedTextureLoading) {
  53229. if (prefiltered) {
  53230. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53231. }
  53232. else {
  53233. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53234. }
  53235. }
  53236. else {
  53237. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53238. }
  53239. }
  53240. else if (onLoad) {
  53241. if (_this._texture.isReady) {
  53242. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53243. }
  53244. else {
  53245. _this._texture.onLoadedObservable.add(onLoad);
  53246. }
  53247. }
  53248. return _this;
  53249. }
  53250. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53251. return new CubeTexture("", scene, null, noMipmap, files);
  53252. };
  53253. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53254. if (forcedExtension === void 0) { forcedExtension = null; }
  53255. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53256. };
  53257. // Methods
  53258. CubeTexture.prototype.delayLoad = function () {
  53259. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53260. return;
  53261. }
  53262. var scene = this.getScene();
  53263. if (!scene) {
  53264. return;
  53265. }
  53266. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53267. this._texture = this._getFromCache(this.url, this._noMipmap);
  53268. if (!this._texture) {
  53269. if (this._prefiltered) {
  53270. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53271. }
  53272. else {
  53273. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53274. }
  53275. }
  53276. };
  53277. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53278. return this._textureMatrix;
  53279. };
  53280. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53281. this._textureMatrix = value;
  53282. };
  53283. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53284. var texture = BABYLON.SerializationHelper.Parse(function () {
  53285. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53286. }, parsedTexture, scene);
  53287. // Animations
  53288. if (parsedTexture.animations) {
  53289. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53290. var parsedAnimation = parsedTexture.animations[animationIndex];
  53291. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53292. }
  53293. }
  53294. return texture;
  53295. };
  53296. CubeTexture.prototype.clone = function () {
  53297. var _this = this;
  53298. return BABYLON.SerializationHelper.Clone(function () {
  53299. var scene = _this.getScene();
  53300. if (!scene) {
  53301. return _this;
  53302. }
  53303. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53304. }, this);
  53305. };
  53306. return CubeTexture;
  53307. }(BABYLON.BaseTexture));
  53308. BABYLON.CubeTexture = CubeTexture;
  53309. })(BABYLON || (BABYLON = {}));
  53310. //# sourceMappingURL=babylon.cubeTexture.js.map
  53311. var BABYLON;
  53312. (function (BABYLON) {
  53313. var RenderTargetTexture = /** @class */ (function (_super) {
  53314. __extends(RenderTargetTexture, _super);
  53315. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53316. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53317. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53318. if (isCube === void 0) { isCube = false; }
  53319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53320. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53321. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53322. if (isMulti === void 0) { isMulti = false; }
  53323. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53324. _this.isCube = isCube;
  53325. /**
  53326. * Use this list to define the list of mesh you want to render.
  53327. */
  53328. _this.renderList = new Array();
  53329. _this.renderParticles = true;
  53330. _this.renderSprites = false;
  53331. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53332. _this.ignoreCameraViewport = false;
  53333. // Events
  53334. /**
  53335. * An event triggered when the texture is unbind.
  53336. * @type {BABYLON.Observable}
  53337. */
  53338. _this.onBeforeBindObservable = new BABYLON.Observable();
  53339. /**
  53340. * An event triggered when the texture is unbind.
  53341. * @type {BABYLON.Observable}
  53342. */
  53343. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53344. /**
  53345. * An event triggered before rendering the texture
  53346. * @type {BABYLON.Observable}
  53347. */
  53348. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53349. /**
  53350. * An event triggered after rendering the texture
  53351. * @type {BABYLON.Observable}
  53352. */
  53353. _this.onAfterRenderObservable = new BABYLON.Observable();
  53354. /**
  53355. * An event triggered after the texture clear
  53356. * @type {BABYLON.Observable}
  53357. */
  53358. _this.onClearObservable = new BABYLON.Observable();
  53359. _this._currentRefreshId = -1;
  53360. _this._refreshRate = 1;
  53361. _this._samples = 1;
  53362. scene = _this.getScene();
  53363. if (!scene) {
  53364. return _this;
  53365. }
  53366. _this._engine = scene.getEngine();
  53367. _this.name = name;
  53368. _this.isRenderTarget = true;
  53369. _this._initialSizeParameter = size;
  53370. _this._processSizeParameter(size);
  53371. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53372. });
  53373. _this._generateMipMaps = generateMipMaps ? true : false;
  53374. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53375. // Rendering groups
  53376. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53377. if (isMulti) {
  53378. return _this;
  53379. }
  53380. _this._renderTargetOptions = {
  53381. generateMipMaps: generateMipMaps,
  53382. type: type,
  53383. samplingMode: samplingMode,
  53384. generateDepthBuffer: generateDepthBuffer,
  53385. generateStencilBuffer: generateStencilBuffer
  53386. };
  53387. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53388. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53389. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53390. }
  53391. if (isCube) {
  53392. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53393. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53394. _this._textureMatrix = BABYLON.Matrix.Identity();
  53395. }
  53396. else {
  53397. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53398. }
  53399. return _this;
  53400. }
  53401. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53402. get: function () {
  53403. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53404. },
  53405. enumerable: true,
  53406. configurable: true
  53407. });
  53408. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  53409. get: function () {
  53410. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  53411. },
  53412. enumerable: true,
  53413. configurable: true
  53414. });
  53415. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  53416. get: function () {
  53417. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  53418. },
  53419. enumerable: true,
  53420. configurable: true
  53421. });
  53422. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  53423. set: function (callback) {
  53424. if (this._onAfterUnbindObserver) {
  53425. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  53426. }
  53427. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  53428. },
  53429. enumerable: true,
  53430. configurable: true
  53431. });
  53432. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  53433. set: function (callback) {
  53434. if (this._onBeforeRenderObserver) {
  53435. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53436. }
  53437. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53438. },
  53439. enumerable: true,
  53440. configurable: true
  53441. });
  53442. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  53443. set: function (callback) {
  53444. if (this._onAfterRenderObserver) {
  53445. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53446. }
  53447. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53448. },
  53449. enumerable: true,
  53450. configurable: true
  53451. });
  53452. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  53453. set: function (callback) {
  53454. if (this._onClearObserver) {
  53455. this.onClearObservable.remove(this._onClearObserver);
  53456. }
  53457. this._onClearObserver = this.onClearObservable.add(callback);
  53458. },
  53459. enumerable: true,
  53460. configurable: true
  53461. });
  53462. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  53463. get: function () {
  53464. return this._renderTargetOptions;
  53465. },
  53466. enumerable: true,
  53467. configurable: true
  53468. });
  53469. RenderTargetTexture.prototype._onRatioRescale = function () {
  53470. if (this._sizeRatio) {
  53471. this.resize(this._initialSizeParameter);
  53472. }
  53473. };
  53474. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  53475. if (size.ratio) {
  53476. this._sizeRatio = size.ratio;
  53477. this._size = {
  53478. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  53479. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  53480. };
  53481. }
  53482. else {
  53483. this._size = size;
  53484. }
  53485. };
  53486. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  53487. get: function () {
  53488. return this._samples;
  53489. },
  53490. set: function (value) {
  53491. if (this._samples === value) {
  53492. return;
  53493. }
  53494. var scene = this.getScene();
  53495. if (!scene) {
  53496. return;
  53497. }
  53498. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  53499. },
  53500. enumerable: true,
  53501. configurable: true
  53502. });
  53503. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  53504. this._currentRefreshId = -1;
  53505. };
  53506. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  53507. get: function () {
  53508. return this._refreshRate;
  53509. },
  53510. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53511. set: function (value) {
  53512. this._refreshRate = value;
  53513. this.resetRefreshCounter();
  53514. },
  53515. enumerable: true,
  53516. configurable: true
  53517. });
  53518. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  53519. if (!this._postProcessManager) {
  53520. var scene = this.getScene();
  53521. if (!scene) {
  53522. return;
  53523. }
  53524. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  53525. this._postProcesses = new Array();
  53526. }
  53527. this._postProcesses.push(postProcess);
  53528. this._postProcesses[0].autoClear = false;
  53529. };
  53530. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  53531. if (!this._postProcesses) {
  53532. return;
  53533. }
  53534. if (dispose) {
  53535. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  53536. var postProcess = _a[_i];
  53537. postProcess.dispose();
  53538. }
  53539. }
  53540. this._postProcesses = [];
  53541. };
  53542. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  53543. if (!this._postProcesses) {
  53544. return;
  53545. }
  53546. var index = this._postProcesses.indexOf(postProcess);
  53547. if (index === -1) {
  53548. return;
  53549. }
  53550. this._postProcesses.splice(index, 1);
  53551. if (this._postProcesses.length > 0) {
  53552. this._postProcesses[0].autoClear = false;
  53553. }
  53554. };
  53555. RenderTargetTexture.prototype._shouldRender = function () {
  53556. if (this._currentRefreshId === -1) {
  53557. this._currentRefreshId = 1;
  53558. return true;
  53559. }
  53560. if (this.refreshRate === this._currentRefreshId) {
  53561. this._currentRefreshId = 1;
  53562. return true;
  53563. }
  53564. this._currentRefreshId++;
  53565. return false;
  53566. };
  53567. RenderTargetTexture.prototype.getRenderSize = function () {
  53568. if (this._size.width) {
  53569. return this._size.width;
  53570. }
  53571. return this._size;
  53572. };
  53573. RenderTargetTexture.prototype.getRenderWidth = function () {
  53574. if (this._size.width) {
  53575. return this._size.width;
  53576. }
  53577. return this._size;
  53578. };
  53579. RenderTargetTexture.prototype.getRenderHeight = function () {
  53580. if (this._size.width) {
  53581. return this._size.height;
  53582. }
  53583. return this._size;
  53584. };
  53585. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  53586. get: function () {
  53587. return true;
  53588. },
  53589. enumerable: true,
  53590. configurable: true
  53591. });
  53592. RenderTargetTexture.prototype.scale = function (ratio) {
  53593. var newSize = this.getRenderSize() * ratio;
  53594. this.resize(newSize);
  53595. };
  53596. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  53597. if (this.isCube) {
  53598. return this._textureMatrix;
  53599. }
  53600. return _super.prototype.getReflectionTextureMatrix.call(this);
  53601. };
  53602. RenderTargetTexture.prototype.resize = function (size) {
  53603. this.releaseInternalTexture();
  53604. var scene = this.getScene();
  53605. if (!scene) {
  53606. return;
  53607. }
  53608. this._processSizeParameter(size);
  53609. if (this.isCube) {
  53610. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  53611. }
  53612. else {
  53613. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  53614. }
  53615. };
  53616. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  53617. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  53618. if (dumpForDebug === void 0) { dumpForDebug = false; }
  53619. var scene = this.getScene();
  53620. if (!scene) {
  53621. return;
  53622. }
  53623. var engine = scene.getEngine();
  53624. if (this.useCameraPostProcesses !== undefined) {
  53625. useCameraPostProcess = this.useCameraPostProcesses;
  53626. }
  53627. if (this._waitingRenderList) {
  53628. this.renderList = [];
  53629. for (var index = 0; index < this._waitingRenderList.length; index++) {
  53630. var id = this._waitingRenderList[index];
  53631. var mesh_1 = scene.getMeshByID(id);
  53632. if (mesh_1) {
  53633. this.renderList.push(mesh_1);
  53634. }
  53635. }
  53636. delete this._waitingRenderList;
  53637. }
  53638. // Is predicate defined?
  53639. if (this.renderListPredicate) {
  53640. if (this.renderList) {
  53641. this.renderList.splice(0); // Clear previous renderList
  53642. }
  53643. else {
  53644. this.renderList = [];
  53645. }
  53646. var scene = this.getScene();
  53647. if (!scene) {
  53648. return;
  53649. }
  53650. var sceneMeshes = scene.meshes;
  53651. for (var index = 0; index < sceneMeshes.length; index++) {
  53652. var mesh = sceneMeshes[index];
  53653. if (this.renderListPredicate(mesh)) {
  53654. this.renderList.push(mesh);
  53655. }
  53656. }
  53657. }
  53658. this.onBeforeBindObservable.notifyObservers(this);
  53659. // Set custom projection.
  53660. // Needs to be before binding to prevent changing the aspect ratio.
  53661. var camera;
  53662. if (this.activeCamera) {
  53663. camera = this.activeCamera;
  53664. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53665. if (this.activeCamera !== scene.activeCamera) {
  53666. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  53667. }
  53668. }
  53669. else {
  53670. camera = scene.activeCamera;
  53671. if (camera) {
  53672. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53673. }
  53674. }
  53675. // Prepare renderingManager
  53676. this._renderingManager.reset();
  53677. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  53678. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  53679. var sceneRenderId = scene.getRenderId();
  53680. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  53681. var mesh = currentRenderList[meshIndex];
  53682. if (mesh) {
  53683. if (!mesh.isReady()) {
  53684. // Reset _currentRefreshId
  53685. this.resetRefreshCounter();
  53686. continue;
  53687. }
  53688. mesh._preActivateForIntermediateRendering(sceneRenderId);
  53689. var isMasked = void 0;
  53690. if (!this.renderList && camera) {
  53691. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  53692. }
  53693. else {
  53694. isMasked = false;
  53695. }
  53696. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  53697. mesh._activate(sceneRenderId);
  53698. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  53699. var subMesh = mesh.subMeshes[subIndex];
  53700. scene._activeIndices.addCount(subMesh.indexCount, false);
  53701. this._renderingManager.dispatch(subMesh, mesh);
  53702. }
  53703. }
  53704. }
  53705. }
  53706. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  53707. var particleSystem = scene.particleSystems[particleIndex];
  53708. var emitter = particleSystem.emitter;
  53709. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  53710. continue;
  53711. }
  53712. if (currentRenderList.indexOf(emitter) >= 0) {
  53713. this._renderingManager.dispatchParticles(particleSystem);
  53714. }
  53715. }
  53716. if (this.isCube) {
  53717. for (var face = 0; face < 6; face++) {
  53718. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53719. scene.incrementRenderId();
  53720. scene.resetCachedMaterial();
  53721. }
  53722. }
  53723. else {
  53724. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53725. }
  53726. this.onAfterUnbindObservable.notifyObservers(this);
  53727. if (scene.activeCamera) {
  53728. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  53729. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  53730. }
  53731. engine.setViewport(scene.activeCamera.viewport);
  53732. }
  53733. scene.resetCachedMaterial();
  53734. };
  53735. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  53736. var minimum = 128;
  53737. var x = renderDimension * scale;
  53738. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  53739. // Ensure we don't exceed the render dimension (while staying POT)
  53740. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  53741. };
  53742. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  53743. var _this = this;
  53744. if (!this._texture) {
  53745. return;
  53746. }
  53747. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  53748. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  53749. });
  53750. };
  53751. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  53752. var scene = this.getScene();
  53753. if (!scene) {
  53754. return;
  53755. }
  53756. var engine = scene.getEngine();
  53757. if (!this._texture) {
  53758. return;
  53759. }
  53760. // Bind
  53761. if (this._postProcessManager) {
  53762. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  53763. }
  53764. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  53765. if (this._texture) {
  53766. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  53767. }
  53768. }
  53769. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  53770. // Clear
  53771. if (this.onClearObservable.hasObservers()) {
  53772. this.onClearObservable.notifyObservers(engine);
  53773. }
  53774. else {
  53775. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  53776. }
  53777. if (!this._doNotChangeAspectRatio) {
  53778. scene.updateTransformMatrix(true);
  53779. }
  53780. // Render
  53781. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  53782. if (this._postProcessManager) {
  53783. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  53784. }
  53785. else if (useCameraPostProcess) {
  53786. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  53787. }
  53788. if (!this._doNotChangeAspectRatio) {
  53789. scene.updateTransformMatrix(true);
  53790. }
  53791. // Dump ?
  53792. if (dumpForDebug) {
  53793. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  53794. }
  53795. // Unbind
  53796. if (!this.isCube || faceIndex === 5) {
  53797. if (this.isCube) {
  53798. if (faceIndex === 5) {
  53799. engine.generateMipMapsForCubemap(this._texture);
  53800. }
  53801. }
  53802. this.unbindFrameBuffer(engine, faceIndex);
  53803. }
  53804. else {
  53805. this.onAfterRenderObservable.notifyObservers(faceIndex);
  53806. }
  53807. };
  53808. /**
  53809. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  53810. * This allowed control for front to back rendering or reversly depending of the special needs.
  53811. *
  53812. * @param renderingGroupId The rendering group id corresponding to its index
  53813. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  53814. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  53815. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  53816. */
  53817. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  53818. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  53819. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  53820. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  53821. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  53822. };
  53823. /**
  53824. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  53825. *
  53826. * @param renderingGroupId The rendering group id corresponding to its index
  53827. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  53828. */
  53829. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  53830. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  53831. };
  53832. RenderTargetTexture.prototype.clone = function () {
  53833. var textureSize = this.getSize();
  53834. 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);
  53835. // Base texture
  53836. newTexture.hasAlpha = this.hasAlpha;
  53837. newTexture.level = this.level;
  53838. // RenderTarget Texture
  53839. newTexture.coordinatesMode = this.coordinatesMode;
  53840. if (this.renderList) {
  53841. newTexture.renderList = this.renderList.slice(0);
  53842. }
  53843. return newTexture;
  53844. };
  53845. RenderTargetTexture.prototype.serialize = function () {
  53846. if (!this.name) {
  53847. return null;
  53848. }
  53849. var serializationObject = _super.prototype.serialize.call(this);
  53850. serializationObject.renderTargetSize = this.getRenderSize();
  53851. serializationObject.renderList = [];
  53852. if (this.renderList) {
  53853. for (var index = 0; index < this.renderList.length; index++) {
  53854. serializationObject.renderList.push(this.renderList[index].id);
  53855. }
  53856. }
  53857. return serializationObject;
  53858. };
  53859. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  53860. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  53861. var objBuffer = this.getInternalTexture();
  53862. var scene = this.getScene();
  53863. if (objBuffer && scene) {
  53864. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  53865. }
  53866. };
  53867. RenderTargetTexture.prototype.dispose = function () {
  53868. if (this._postProcessManager) {
  53869. this._postProcessManager.dispose();
  53870. this._postProcessManager = null;
  53871. }
  53872. this.clearPostProcesses(true);
  53873. if (this._resizeObserver) {
  53874. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  53875. this._resizeObserver = null;
  53876. }
  53877. this.renderList = null;
  53878. // Remove from custom render targets
  53879. var scene = this.getScene();
  53880. if (!scene) {
  53881. return;
  53882. }
  53883. var index = scene.customRenderTargets.indexOf(this);
  53884. if (index >= 0) {
  53885. scene.customRenderTargets.splice(index, 1);
  53886. }
  53887. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  53888. var camera = _a[_i];
  53889. index = camera.customRenderTargets.indexOf(this);
  53890. if (index >= 0) {
  53891. camera.customRenderTargets.splice(index, 1);
  53892. }
  53893. }
  53894. _super.prototype.dispose.call(this);
  53895. };
  53896. RenderTargetTexture.prototype._rebuild = function () {
  53897. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  53898. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  53899. }
  53900. if (this._postProcessManager) {
  53901. this._postProcessManager._rebuild();
  53902. }
  53903. };
  53904. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  53905. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  53906. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  53907. return RenderTargetTexture;
  53908. }(BABYLON.Texture));
  53909. BABYLON.RenderTargetTexture = RenderTargetTexture;
  53910. })(BABYLON || (BABYLON = {}));
  53911. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  53912. var BABYLON;
  53913. (function (BABYLON) {
  53914. ;
  53915. var MultiRenderTarget = /** @class */ (function (_super) {
  53916. __extends(MultiRenderTarget, _super);
  53917. function MultiRenderTarget(name, size, count, scene, options) {
  53918. var _this = this;
  53919. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  53920. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  53921. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  53922. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  53923. _this._engine = scene.getEngine();
  53924. if (!_this.isSupported) {
  53925. _this.dispose();
  53926. return;
  53927. }
  53928. var types = [];
  53929. var samplingModes = [];
  53930. for (var i = 0; i < count; i++) {
  53931. if (options && options.types && options.types[i] !== undefined) {
  53932. types.push(options.types[i]);
  53933. }
  53934. else {
  53935. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53936. }
  53937. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  53938. samplingModes.push(options.samplingModes[i]);
  53939. }
  53940. else {
  53941. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53942. }
  53943. }
  53944. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  53945. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  53946. _this._size = size;
  53947. _this._multiRenderTargetOptions = {
  53948. samplingModes: samplingModes,
  53949. generateMipMaps: generateMipMaps,
  53950. generateDepthBuffer: generateDepthBuffer,
  53951. generateStencilBuffer: generateStencilBuffer,
  53952. generateDepthTexture: generateDepthTexture,
  53953. types: types,
  53954. textureCount: count
  53955. };
  53956. _this._createInternalTextures();
  53957. _this._createTextures();
  53958. return _this;
  53959. }
  53960. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  53961. get: function () {
  53962. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  53963. },
  53964. enumerable: true,
  53965. configurable: true
  53966. });
  53967. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  53968. get: function () {
  53969. return this._textures;
  53970. },
  53971. enumerable: true,
  53972. configurable: true
  53973. });
  53974. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  53975. get: function () {
  53976. return this._textures[this._textures.length - 1];
  53977. },
  53978. enumerable: true,
  53979. configurable: true
  53980. });
  53981. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  53982. set: function (wrap) {
  53983. if (this._textures) {
  53984. for (var i = 0; i < this._textures.length; i++) {
  53985. this._textures[i].wrapU = wrap;
  53986. }
  53987. }
  53988. },
  53989. enumerable: true,
  53990. configurable: true
  53991. });
  53992. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  53993. set: function (wrap) {
  53994. if (this._textures) {
  53995. for (var i = 0; i < this._textures.length; i++) {
  53996. this._textures[i].wrapV = wrap;
  53997. }
  53998. }
  53999. },
  54000. enumerable: true,
  54001. configurable: true
  54002. });
  54003. MultiRenderTarget.prototype._rebuild = function () {
  54004. this.releaseInternalTextures();
  54005. this._createInternalTextures();
  54006. for (var i = 0; i < this._internalTextures.length; i++) {
  54007. var texture = this._textures[i];
  54008. texture._texture = this._internalTextures[i];
  54009. }
  54010. // Keeps references to frame buffer and stencil/depth buffer
  54011. this._texture = this._internalTextures[0];
  54012. };
  54013. MultiRenderTarget.prototype._createInternalTextures = function () {
  54014. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54015. };
  54016. MultiRenderTarget.prototype._createTextures = function () {
  54017. this._textures = [];
  54018. for (var i = 0; i < this._internalTextures.length; i++) {
  54019. var texture = new BABYLON.Texture(null, this.getScene());
  54020. texture._texture = this._internalTextures[i];
  54021. this._textures.push(texture);
  54022. }
  54023. // Keeps references to frame buffer and stencil/depth buffer
  54024. this._texture = this._internalTextures[0];
  54025. };
  54026. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54027. get: function () {
  54028. return this._samples;
  54029. },
  54030. set: function (value) {
  54031. if (this._samples === value) {
  54032. return;
  54033. }
  54034. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54035. },
  54036. enumerable: true,
  54037. configurable: true
  54038. });
  54039. MultiRenderTarget.prototype.resize = function (size) {
  54040. this.releaseInternalTextures();
  54041. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54042. this._createInternalTextures();
  54043. };
  54044. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54045. var _this = this;
  54046. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54047. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54048. });
  54049. };
  54050. MultiRenderTarget.prototype.dispose = function () {
  54051. this.releaseInternalTextures();
  54052. _super.prototype.dispose.call(this);
  54053. };
  54054. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54055. if (!this._internalTextures) {
  54056. return;
  54057. }
  54058. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54059. if (this._internalTextures[i] !== undefined) {
  54060. this._internalTextures[i].dispose();
  54061. this._internalTextures.splice(i, 1);
  54062. }
  54063. }
  54064. };
  54065. return MultiRenderTarget;
  54066. }(BABYLON.RenderTargetTexture));
  54067. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54068. })(BABYLON || (BABYLON = {}));
  54069. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  54070. var BABYLON;
  54071. (function (BABYLON) {
  54072. var MirrorTexture = /** @class */ (function (_super) {
  54073. __extends(MirrorTexture, _super);
  54074. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  54075. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54077. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54078. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  54079. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  54080. _this._transformMatrix = BABYLON.Matrix.Zero();
  54081. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  54082. _this._adaptiveBlurKernel = 0;
  54083. _this._blurKernelX = 0;
  54084. _this._blurKernelY = 0;
  54085. _this._blurRatio = 1.0;
  54086. _this.ignoreCameraViewport = true;
  54087. _this.onBeforeRenderObservable.add(function () {
  54088. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  54089. _this._savedViewMatrix = scene.getViewMatrix();
  54090. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  54091. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  54092. scene.clipPlane = _this.mirrorPlane;
  54093. scene.getEngine().cullBackFaces = false;
  54094. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  54095. });
  54096. _this.onAfterRenderObservable.add(function () {
  54097. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  54098. scene.getEngine().cullBackFaces = true;
  54099. scene._mirroredCameraPosition = null;
  54100. delete scene.clipPlane;
  54101. });
  54102. return _this;
  54103. }
  54104. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  54105. get: function () {
  54106. return this._blurRatio;
  54107. },
  54108. set: function (value) {
  54109. if (this._blurRatio === value) {
  54110. return;
  54111. }
  54112. this._blurRatio = value;
  54113. this._preparePostProcesses();
  54114. },
  54115. enumerable: true,
  54116. configurable: true
  54117. });
  54118. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  54119. set: function (value) {
  54120. this._adaptiveBlurKernel = value;
  54121. this._autoComputeBlurKernel();
  54122. },
  54123. enumerable: true,
  54124. configurable: true
  54125. });
  54126. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  54127. set: function (value) {
  54128. this.blurKernelX = value;
  54129. this.blurKernelY = value;
  54130. },
  54131. enumerable: true,
  54132. configurable: true
  54133. });
  54134. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  54135. get: function () {
  54136. return this._blurKernelX;
  54137. },
  54138. set: function (value) {
  54139. if (this._blurKernelX === value) {
  54140. return;
  54141. }
  54142. this._blurKernelX = value;
  54143. this._preparePostProcesses();
  54144. },
  54145. enumerable: true,
  54146. configurable: true
  54147. });
  54148. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  54149. get: function () {
  54150. return this._blurKernelY;
  54151. },
  54152. set: function (value) {
  54153. if (this._blurKernelY === value) {
  54154. return;
  54155. }
  54156. this._blurKernelY = value;
  54157. this._preparePostProcesses();
  54158. },
  54159. enumerable: true,
  54160. configurable: true
  54161. });
  54162. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  54163. var engine = this.getScene().getEngine();
  54164. var dw = this.getRenderWidth() / engine.getRenderWidth();
  54165. var dh = this.getRenderHeight() / engine.getRenderHeight();
  54166. this.blurKernelX = this._adaptiveBlurKernel * dw;
  54167. this.blurKernelY = this._adaptiveBlurKernel * dh;
  54168. };
  54169. MirrorTexture.prototype._onRatioRescale = function () {
  54170. if (this._sizeRatio) {
  54171. this.resize(this._initialSizeParameter);
  54172. if (!this._adaptiveBlurKernel) {
  54173. this._preparePostProcesses();
  54174. }
  54175. }
  54176. if (this._adaptiveBlurKernel) {
  54177. this._autoComputeBlurKernel();
  54178. }
  54179. };
  54180. MirrorTexture.prototype._preparePostProcesses = function () {
  54181. this.clearPostProcesses(true);
  54182. if (this._blurKernelX && this._blurKernelY) {
  54183. var engine = this.getScene().getEngine();
  54184. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54185. 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);
  54186. this._blurX.autoClear = false;
  54187. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54188. this._blurX.outputTexture = this._texture;
  54189. }
  54190. else {
  54191. this._blurX.alwaysForcePOT = true;
  54192. }
  54193. 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);
  54194. this._blurY.autoClear = false;
  54195. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54196. this.addPostProcess(this._blurX);
  54197. this.addPostProcess(this._blurY);
  54198. }
  54199. else {
  54200. if (this._blurY) {
  54201. this.removePostProcess(this._blurY);
  54202. this._blurY.dispose();
  54203. this._blurY = null;
  54204. }
  54205. if (this._blurX) {
  54206. this.removePostProcess(this._blurX);
  54207. this._blurX.dispose();
  54208. this._blurX = null;
  54209. }
  54210. }
  54211. };
  54212. MirrorTexture.prototype.clone = function () {
  54213. var scene = this.getScene();
  54214. if (!scene) {
  54215. return this;
  54216. }
  54217. var textureSize = this.getSize();
  54218. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54219. // Base texture
  54220. newTexture.hasAlpha = this.hasAlpha;
  54221. newTexture.level = this.level;
  54222. // Mirror Texture
  54223. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54224. if (this.renderList) {
  54225. newTexture.renderList = this.renderList.slice(0);
  54226. }
  54227. return newTexture;
  54228. };
  54229. MirrorTexture.prototype.serialize = function () {
  54230. if (!this.name) {
  54231. return null;
  54232. }
  54233. var serializationObject = _super.prototype.serialize.call(this);
  54234. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54235. return serializationObject;
  54236. };
  54237. return MirrorTexture;
  54238. }(BABYLON.RenderTargetTexture));
  54239. BABYLON.MirrorTexture = MirrorTexture;
  54240. })(BABYLON || (BABYLON = {}));
  54241. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54242. var BABYLON;
  54243. (function (BABYLON) {
  54244. /**
  54245. * Creates a refraction texture used by refraction channel of the standard material.
  54246. * @param name the texture name
  54247. * @param size size of the underlying texture
  54248. * @param scene root scene
  54249. */
  54250. var RefractionTexture = /** @class */ (function (_super) {
  54251. __extends(RefractionTexture, _super);
  54252. function RefractionTexture(name, size, scene, generateMipMaps) {
  54253. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54254. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54255. _this.depth = 2.0;
  54256. _this.onBeforeRenderObservable.add(function () {
  54257. scene.clipPlane = _this.refractionPlane;
  54258. });
  54259. _this.onAfterRenderObservable.add(function () {
  54260. delete scene.clipPlane;
  54261. });
  54262. return _this;
  54263. }
  54264. RefractionTexture.prototype.clone = function () {
  54265. var scene = this.getScene();
  54266. if (!scene) {
  54267. return this;
  54268. }
  54269. var textureSize = this.getSize();
  54270. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54271. // Base texture
  54272. newTexture.hasAlpha = this.hasAlpha;
  54273. newTexture.level = this.level;
  54274. // Refraction Texture
  54275. newTexture.refractionPlane = this.refractionPlane.clone();
  54276. if (this.renderList) {
  54277. newTexture.renderList = this.renderList.slice(0);
  54278. }
  54279. newTexture.depth = this.depth;
  54280. return newTexture;
  54281. };
  54282. RefractionTexture.prototype.serialize = function () {
  54283. if (!this.name) {
  54284. return null;
  54285. }
  54286. var serializationObject = _super.prototype.serialize.call(this);
  54287. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54288. serializationObject.depth = this.depth;
  54289. return serializationObject;
  54290. };
  54291. return RefractionTexture;
  54292. }(BABYLON.RenderTargetTexture));
  54293. BABYLON.RefractionTexture = RefractionTexture;
  54294. })(BABYLON || (BABYLON = {}));
  54295. //# sourceMappingURL=babylon.refractionTexture.js.map
  54296. var BABYLON;
  54297. (function (BABYLON) {
  54298. var DynamicTexture = /** @class */ (function (_super) {
  54299. __extends(DynamicTexture, _super);
  54300. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54301. if (scene === void 0) { scene = null; }
  54302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54303. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54304. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54305. _this.name = name;
  54306. _this._engine = _this.getScene().getEngine();
  54307. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54308. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54309. _this._generateMipMaps = generateMipMaps;
  54310. if (options.getContext) {
  54311. _this._canvas = options;
  54312. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54313. }
  54314. else {
  54315. _this._canvas = document.createElement("canvas");
  54316. if (options.width) {
  54317. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54318. }
  54319. else {
  54320. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54321. }
  54322. }
  54323. var textureSize = _this.getSize();
  54324. _this._canvas.width = textureSize.width;
  54325. _this._canvas.height = textureSize.height;
  54326. _this._context = _this._canvas.getContext("2d");
  54327. return _this;
  54328. }
  54329. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54330. get: function () {
  54331. return true;
  54332. },
  54333. enumerable: true,
  54334. configurable: true
  54335. });
  54336. DynamicTexture.prototype._recreate = function (textureSize) {
  54337. this._canvas.width = textureSize.width;
  54338. this._canvas.height = textureSize.height;
  54339. this.releaseInternalTexture();
  54340. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54341. };
  54342. DynamicTexture.prototype.scale = function (ratio) {
  54343. var textureSize = this.getSize();
  54344. textureSize.width *= ratio;
  54345. textureSize.height *= ratio;
  54346. this._recreate(textureSize);
  54347. };
  54348. DynamicTexture.prototype.scaleTo = function (width, height) {
  54349. var textureSize = this.getSize();
  54350. textureSize.width = width;
  54351. textureSize.height = height;
  54352. this._recreate(textureSize);
  54353. };
  54354. DynamicTexture.prototype.getContext = function () {
  54355. return this._context;
  54356. };
  54357. DynamicTexture.prototype.clear = function () {
  54358. var size = this.getSize();
  54359. this._context.fillRect(0, 0, size.width, size.height);
  54360. };
  54361. DynamicTexture.prototype.update = function (invertY) {
  54362. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54363. };
  54364. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54365. if (update === void 0) { update = true; }
  54366. var size = this.getSize();
  54367. if (clearColor) {
  54368. this._context.fillStyle = clearColor;
  54369. this._context.fillRect(0, 0, size.width, size.height);
  54370. }
  54371. this._context.font = font;
  54372. if (x === null || x === undefined) {
  54373. var textSize = this._context.measureText(text);
  54374. x = (size.width - textSize.width) / 2;
  54375. }
  54376. if (y === null || y === undefined) {
  54377. var fontSize = parseInt((font.replace(/\D/g, '')));
  54378. ;
  54379. y = (size.height / 2) + (fontSize / 3.65);
  54380. }
  54381. this._context.fillStyle = color;
  54382. this._context.fillText(text, x, y);
  54383. if (update) {
  54384. this.update(invertY);
  54385. }
  54386. };
  54387. DynamicTexture.prototype.clone = function () {
  54388. var scene = this.getScene();
  54389. if (!scene) {
  54390. return this;
  54391. }
  54392. var textureSize = this.getSize();
  54393. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54394. // Base texture
  54395. newTexture.hasAlpha = this.hasAlpha;
  54396. newTexture.level = this.level;
  54397. // Dynamic Texture
  54398. newTexture.wrapU = this.wrapU;
  54399. newTexture.wrapV = this.wrapV;
  54400. return newTexture;
  54401. };
  54402. DynamicTexture.prototype._rebuild = function () {
  54403. this.update();
  54404. };
  54405. return DynamicTexture;
  54406. }(BABYLON.Texture));
  54407. BABYLON.DynamicTexture = DynamicTexture;
  54408. })(BABYLON || (BABYLON = {}));
  54409. //# sourceMappingURL=babylon.dynamicTexture.js.map
  54410. var BABYLON;
  54411. (function (BABYLON) {
  54412. var VideoTexture = /** @class */ (function (_super) {
  54413. __extends(VideoTexture, _super);
  54414. /**
  54415. * Creates a video texture.
  54416. * Sample : https://doc.babylonjs.com/how_to/video_texture
  54417. * @param {string | null} name optional name, will detect from video source, if not defined
  54418. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  54419. * @param {BABYLON.Scene} scene is obviously the current scene.
  54420. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  54421. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  54422. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  54423. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  54424. */
  54425. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  54426. if (generateMipMaps === void 0) { generateMipMaps = false; }
  54427. if (invertY === void 0) { invertY = false; }
  54428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54429. if (settings === void 0) { settings = {
  54430. autoPlay: true,
  54431. loop: true,
  54432. autoUpdateTexture: true,
  54433. }; }
  54434. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54435. _this._createInternalTexture = function () {
  54436. if (_this._texture != null) {
  54437. return;
  54438. }
  54439. if (!_this._engine.needPOTTextures ||
  54440. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  54441. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54442. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54443. }
  54444. else {
  54445. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54446. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54447. _this._generateMipMaps = false;
  54448. }
  54449. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  54450. _this._texture.width;
  54451. _this._updateInternalTexture();
  54452. _this._texture.isReady = true;
  54453. };
  54454. _this.reset = function () {
  54455. if (_this._texture == null) {
  54456. return;
  54457. }
  54458. _this._texture.dispose();
  54459. _this._texture = null;
  54460. };
  54461. _this._updateInternalTexture = function (e) {
  54462. if (_this._texture == null || !_this._texture.isReady) {
  54463. return;
  54464. }
  54465. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  54466. return;
  54467. }
  54468. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  54469. };
  54470. _this._engine = _this.getScene().getEngine();
  54471. _this._generateMipMaps = generateMipMaps;
  54472. _this._samplingMode = samplingMode;
  54473. _this.autoUpdateTexture = settings.autoUpdateTexture;
  54474. _this.name = name || _this._getName(src);
  54475. _this.video = _this._getVideo(src);
  54476. if (settings.autoPlay !== undefined) {
  54477. _this.video.autoplay = settings.autoPlay;
  54478. }
  54479. if (settings.loop !== undefined) {
  54480. _this.video.loop = settings.loop;
  54481. }
  54482. _this.video.addEventListener("canplay", _this._createInternalTexture);
  54483. _this.video.addEventListener("paused", _this._updateInternalTexture);
  54484. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  54485. _this.video.addEventListener("emptied", _this.reset);
  54486. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  54487. _this._createInternalTexture();
  54488. }
  54489. return _this;
  54490. }
  54491. VideoTexture.prototype._getName = function (src) {
  54492. if (src instanceof HTMLVideoElement) {
  54493. return src.currentSrc;
  54494. }
  54495. if (typeof src === "object") {
  54496. return src.toString();
  54497. }
  54498. return src;
  54499. };
  54500. ;
  54501. VideoTexture.prototype._getVideo = function (src) {
  54502. if (src instanceof HTMLVideoElement) {
  54503. return src;
  54504. }
  54505. var video = document.createElement("video");
  54506. if (typeof src === "string") {
  54507. video.src = src;
  54508. }
  54509. else {
  54510. src.forEach(function (url) {
  54511. var source = document.createElement("source");
  54512. source.src = url;
  54513. video.appendChild(source);
  54514. });
  54515. }
  54516. return video;
  54517. };
  54518. ;
  54519. /**
  54520. * Internal method to initiate `update`.
  54521. */
  54522. VideoTexture.prototype._rebuild = function () {
  54523. this.update();
  54524. };
  54525. /**
  54526. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  54527. */
  54528. VideoTexture.prototype.update = function () {
  54529. if (!this.autoUpdateTexture) {
  54530. // Expecting user to call `updateTexture` manually
  54531. return;
  54532. }
  54533. this.updateTexture(true);
  54534. };
  54535. /**
  54536. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  54537. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  54538. */
  54539. VideoTexture.prototype.updateTexture = function (isVisible) {
  54540. if (!isVisible) {
  54541. return;
  54542. }
  54543. if (this.video.paused) {
  54544. return;
  54545. }
  54546. this._updateInternalTexture();
  54547. };
  54548. /**
  54549. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  54550. * @param url New url.
  54551. */
  54552. VideoTexture.prototype.updateURL = function (url) {
  54553. this.video.src = url;
  54554. };
  54555. VideoTexture.prototype.dispose = function () {
  54556. _super.prototype.dispose.call(this);
  54557. this.video.removeEventListener("canplay", this._createInternalTexture);
  54558. this.video.removeEventListener("paused", this._updateInternalTexture);
  54559. this.video.removeEventListener("seeked", this._updateInternalTexture);
  54560. this.video.removeEventListener("emptied", this.reset);
  54561. };
  54562. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  54563. var video = document.createElement("video");
  54564. var constraintsDeviceId;
  54565. if (constraints && constraints.deviceId) {
  54566. constraintsDeviceId = {
  54567. exact: constraints.deviceId,
  54568. };
  54569. }
  54570. navigator.getUserMedia =
  54571. navigator.getUserMedia ||
  54572. navigator.webkitGetUserMedia ||
  54573. navigator.mozGetUserMedia ||
  54574. navigator.msGetUserMedia;
  54575. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  54576. if (navigator.getUserMedia) {
  54577. navigator.getUserMedia({
  54578. video: {
  54579. deviceId: constraintsDeviceId,
  54580. width: {
  54581. min: (constraints && constraints.minWidth) || 256,
  54582. max: (constraints && constraints.maxWidth) || 640,
  54583. },
  54584. height: {
  54585. min: (constraints && constraints.minHeight) || 256,
  54586. max: (constraints && constraints.maxHeight) || 480,
  54587. },
  54588. },
  54589. }, function (stream) {
  54590. if (video.mozSrcObject !== undefined) {
  54591. // hack for Firefox < 19
  54592. video.mozSrcObject = stream;
  54593. }
  54594. else {
  54595. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  54596. }
  54597. video.play();
  54598. if (onReady) {
  54599. onReady(new VideoTexture("video", video, scene, true, true));
  54600. }
  54601. }, function (e) {
  54602. BABYLON.Tools.Error(e.name);
  54603. });
  54604. }
  54605. };
  54606. return VideoTexture;
  54607. }(BABYLON.Texture));
  54608. BABYLON.VideoTexture = VideoTexture;
  54609. })(BABYLON || (BABYLON = {}));
  54610. //# sourceMappingURL=babylon.videoTexture.js.map
  54611. var BABYLON;
  54612. (function (BABYLON) {
  54613. var RawTexture = /** @class */ (function (_super) {
  54614. __extends(RawTexture, _super);
  54615. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  54616. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54617. if (invertY === void 0) { invertY = false; }
  54618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54619. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54620. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54621. _this.format = format;
  54622. _this._engine = scene.getEngine();
  54623. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  54624. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54625. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54626. return _this;
  54627. }
  54628. RawTexture.prototype.update = function (data) {
  54629. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  54630. };
  54631. // Statics
  54632. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54633. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54634. if (invertY === void 0) { invertY = false; }
  54635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54636. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54637. };
  54638. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54639. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54640. if (invertY === void 0) { invertY = false; }
  54641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54642. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54643. };
  54644. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54645. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54646. if (invertY === void 0) { invertY = false; }
  54647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54648. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54649. };
  54650. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54651. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54652. if (invertY === void 0) { invertY = false; }
  54653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54654. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54655. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  54656. };
  54657. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54658. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54659. if (invertY === void 0) { invertY = false; }
  54660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54661. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54662. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  54663. };
  54664. return RawTexture;
  54665. }(BABYLON.Texture));
  54666. BABYLON.RawTexture = RawTexture;
  54667. })(BABYLON || (BABYLON = {}));
  54668. //# sourceMappingURL=babylon.rawTexture.js.map
  54669. var BABYLON;
  54670. (function (BABYLON) {
  54671. var PostProcess = /** @class */ (function () {
  54672. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  54673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  54674. if (defines === void 0) { defines = null; }
  54675. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54676. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  54677. if (blockCompilation === void 0) { blockCompilation = false; }
  54678. this.name = name;
  54679. this.width = -1;
  54680. this.height = -1;
  54681. this.autoClear = true;
  54682. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  54683. this.animations = new Array();
  54684. /*
  54685. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  54686. Can only be used on a single postprocess or on the last one of a chain.
  54687. */
  54688. this.enablePixelPerfectMode = false;
  54689. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  54690. this.alwaysForcePOT = false;
  54691. this.samples = 1;
  54692. this.adaptScaleToCurrentViewport = false;
  54693. this._reusable = false;
  54694. this._textures = new BABYLON.SmartArray(2);
  54695. this._currentRenderTextureInd = 0;
  54696. this._scaleRatio = new BABYLON.Vector2(1, 1);
  54697. this._texelSize = BABYLON.Vector2.Zero();
  54698. // Events
  54699. /**
  54700. * An event triggered when the postprocess is activated.
  54701. * @type {BABYLON.Observable}
  54702. */
  54703. this.onActivateObservable = new BABYLON.Observable();
  54704. /**
  54705. * An event triggered when the postprocess changes its size.
  54706. * @type {BABYLON.Observable}
  54707. */
  54708. this.onSizeChangedObservable = new BABYLON.Observable();
  54709. /**
  54710. * An event triggered when the postprocess applies its effect.
  54711. * @type {BABYLON.Observable}
  54712. */
  54713. this.onApplyObservable = new BABYLON.Observable();
  54714. /**
  54715. * An event triggered before rendering the postprocess
  54716. * @type {BABYLON.Observable}
  54717. */
  54718. this.onBeforeRenderObservable = new BABYLON.Observable();
  54719. /**
  54720. * An event triggered after rendering the postprocess
  54721. * @type {BABYLON.Observable}
  54722. */
  54723. this.onAfterRenderObservable = new BABYLON.Observable();
  54724. if (camera != null) {
  54725. this._camera = camera;
  54726. this._scene = camera.getScene();
  54727. camera.attachPostProcess(this);
  54728. this._engine = this._scene.getEngine();
  54729. this._scene.postProcesses.push(this);
  54730. }
  54731. else if (engine) {
  54732. this._engine = engine;
  54733. this._engine.postProcesses.push(this);
  54734. }
  54735. this._options = options;
  54736. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  54737. this._reusable = reusable || false;
  54738. this._textureType = textureType;
  54739. this._samplers = samplers || [];
  54740. this._samplers.push("textureSampler");
  54741. this._fragmentUrl = fragmentUrl;
  54742. this._vertexUrl = vertexUrl;
  54743. this._parameters = parameters || [];
  54744. this._parameters.push("scale");
  54745. this._indexParameters = indexParameters;
  54746. if (!blockCompilation) {
  54747. this.updateEffect(defines);
  54748. }
  54749. }
  54750. Object.defineProperty(PostProcess.prototype, "onActivate", {
  54751. set: function (callback) {
  54752. if (this._onActivateObserver) {
  54753. this.onActivateObservable.remove(this._onActivateObserver);
  54754. }
  54755. if (callback) {
  54756. this._onActivateObserver = this.onActivateObservable.add(callback);
  54757. }
  54758. },
  54759. enumerable: true,
  54760. configurable: true
  54761. });
  54762. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  54763. set: function (callback) {
  54764. if (this._onSizeChangedObserver) {
  54765. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  54766. }
  54767. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  54768. },
  54769. enumerable: true,
  54770. configurable: true
  54771. });
  54772. Object.defineProperty(PostProcess.prototype, "onApply", {
  54773. set: function (callback) {
  54774. if (this._onApplyObserver) {
  54775. this.onApplyObservable.remove(this._onApplyObserver);
  54776. }
  54777. this._onApplyObserver = this.onApplyObservable.add(callback);
  54778. },
  54779. enumerable: true,
  54780. configurable: true
  54781. });
  54782. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  54783. set: function (callback) {
  54784. if (this._onBeforeRenderObserver) {
  54785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54786. }
  54787. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54788. },
  54789. enumerable: true,
  54790. configurable: true
  54791. });
  54792. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  54793. set: function (callback) {
  54794. if (this._onAfterRenderObserver) {
  54795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54796. }
  54797. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54798. },
  54799. enumerable: true,
  54800. configurable: true
  54801. });
  54802. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  54803. get: function () {
  54804. return this._textures.data[this._currentRenderTextureInd];
  54805. },
  54806. set: function (value) {
  54807. this._forcedOutputTexture = value;
  54808. },
  54809. enumerable: true,
  54810. configurable: true
  54811. });
  54812. PostProcess.prototype.getCamera = function () {
  54813. return this._camera;
  54814. };
  54815. Object.defineProperty(PostProcess.prototype, "texelSize", {
  54816. get: function () {
  54817. if (this._shareOutputWithPostProcess) {
  54818. return this._shareOutputWithPostProcess.texelSize;
  54819. }
  54820. if (this._forcedOutputTexture) {
  54821. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  54822. }
  54823. return this._texelSize;
  54824. },
  54825. enumerable: true,
  54826. configurable: true
  54827. });
  54828. PostProcess.prototype.getEngine = function () {
  54829. return this._engine;
  54830. };
  54831. PostProcess.prototype.getEffect = function () {
  54832. return this._effect;
  54833. };
  54834. PostProcess.prototype.shareOutputWith = function (postProcess) {
  54835. this._disposeTextures();
  54836. this._shareOutputWithPostProcess = postProcess;
  54837. return this;
  54838. };
  54839. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  54840. if (defines === void 0) { defines = null; }
  54841. if (uniforms === void 0) { uniforms = null; }
  54842. if (samplers === void 0) { samplers = null; }
  54843. 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);
  54844. };
  54845. PostProcess.prototype.isReusable = function () {
  54846. return this._reusable;
  54847. };
  54848. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  54849. PostProcess.prototype.markTextureDirty = function () {
  54850. this.width = -1;
  54851. };
  54852. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  54853. var _this = this;
  54854. if (sourceTexture === void 0) { sourceTexture = null; }
  54855. camera = camera || this._camera;
  54856. var scene = camera.getScene();
  54857. var engine = scene.getEngine();
  54858. var maxSize = engine.getCaps().maxTextureSize;
  54859. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  54860. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  54861. var desiredWidth = (this._options.width || requiredWidth);
  54862. var desiredHeight = this._options.height || requiredHeight;
  54863. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  54864. if (this.adaptScaleToCurrentViewport) {
  54865. var currentViewport = engine.currentViewport;
  54866. if (currentViewport) {
  54867. desiredWidth *= currentViewport.width;
  54868. desiredHeight *= currentViewport.height;
  54869. }
  54870. }
  54871. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  54872. if (!this._options.width) {
  54873. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  54874. }
  54875. if (!this._options.height) {
  54876. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  54877. }
  54878. }
  54879. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  54880. if (this._textures.length > 0) {
  54881. for (var i = 0; i < this._textures.length; i++) {
  54882. this._engine._releaseTexture(this._textures.data[i]);
  54883. }
  54884. this._textures.reset();
  54885. }
  54886. this.width = desiredWidth;
  54887. this.height = desiredHeight;
  54888. var textureSize = { width: this.width, height: this.height };
  54889. var textureOptions = {
  54890. generateMipMaps: false,
  54891. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  54892. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  54893. samplingMode: this.renderTargetSamplingMode,
  54894. type: this._textureType
  54895. };
  54896. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54897. if (this._reusable) {
  54898. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54899. }
  54900. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  54901. this.onSizeChangedObservable.notifyObservers(this);
  54902. }
  54903. this._textures.forEach(function (texture) {
  54904. if (texture.samples !== _this.samples) {
  54905. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  54906. }
  54907. });
  54908. }
  54909. var target;
  54910. if (this._shareOutputWithPostProcess) {
  54911. target = this._shareOutputWithPostProcess.outputTexture;
  54912. }
  54913. else if (this._forcedOutputTexture) {
  54914. target = this._forcedOutputTexture;
  54915. this.width = this._forcedOutputTexture.width;
  54916. this.height = this._forcedOutputTexture.height;
  54917. }
  54918. else {
  54919. target = this.outputTexture;
  54920. }
  54921. if (this.enablePixelPerfectMode) {
  54922. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  54923. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  54924. }
  54925. else {
  54926. this._scaleRatio.copyFromFloats(1, 1);
  54927. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  54928. }
  54929. this.onActivateObservable.notifyObservers(camera);
  54930. // Clear
  54931. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  54932. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  54933. }
  54934. if (this._reusable) {
  54935. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  54936. }
  54937. };
  54938. Object.defineProperty(PostProcess.prototype, "isSupported", {
  54939. get: function () {
  54940. return this._effect.isSupported;
  54941. },
  54942. enumerable: true,
  54943. configurable: true
  54944. });
  54945. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  54946. get: function () {
  54947. if (this._shareOutputWithPostProcess) {
  54948. return this._shareOutputWithPostProcess.aspectRatio;
  54949. }
  54950. if (this._forcedOutputTexture) {
  54951. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  54952. }
  54953. return this.width / this.height;
  54954. },
  54955. enumerable: true,
  54956. configurable: true
  54957. });
  54958. /**
  54959. * Get a value indicating if the post-process is ready to be used
  54960. * @returns true if the post-process is ready (shader is compiled)
  54961. */
  54962. PostProcess.prototype.isReady = function () {
  54963. return this._effect && this._effect.isReady();
  54964. };
  54965. PostProcess.prototype.apply = function () {
  54966. // Check
  54967. if (!this._effect || !this._effect.isReady())
  54968. return null;
  54969. // States
  54970. this._engine.enableEffect(this._effect);
  54971. this._engine.setState(false);
  54972. this._engine.setDepthBuffer(false);
  54973. this._engine.setDepthWrite(false);
  54974. // Alpha
  54975. this._engine.setAlphaMode(this.alphaMode);
  54976. if (this.alphaConstants) {
  54977. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  54978. }
  54979. // Texture
  54980. var source;
  54981. if (this._shareOutputWithPostProcess) {
  54982. source = this._shareOutputWithPostProcess.outputTexture;
  54983. }
  54984. else if (this._forcedOutputTexture) {
  54985. source = this._forcedOutputTexture;
  54986. }
  54987. else {
  54988. source = this.outputTexture;
  54989. }
  54990. this._effect._bindTexture("textureSampler", source);
  54991. // Parameters
  54992. this._effect.setVector2("scale", this._scaleRatio);
  54993. this.onApplyObservable.notifyObservers(this._effect);
  54994. return this._effect;
  54995. };
  54996. PostProcess.prototype._disposeTextures = function () {
  54997. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  54998. return;
  54999. }
  55000. if (this._textures.length > 0) {
  55001. for (var i = 0; i < this._textures.length; i++) {
  55002. this._engine._releaseTexture(this._textures.data[i]);
  55003. }
  55004. }
  55005. this._textures.dispose();
  55006. };
  55007. PostProcess.prototype.dispose = function (camera) {
  55008. camera = camera || this._camera;
  55009. this._disposeTextures();
  55010. if (this._scene) {
  55011. var index_1 = this._scene.postProcesses.indexOf(this);
  55012. if (index_1 !== -1) {
  55013. this._scene.postProcesses.splice(index_1, 1);
  55014. }
  55015. }
  55016. else {
  55017. var index_2 = this._engine.postProcesses.indexOf(this);
  55018. if (index_2 !== -1) {
  55019. this._engine.postProcesses.splice(index_2, 1);
  55020. }
  55021. }
  55022. if (!camera) {
  55023. return;
  55024. }
  55025. camera.detachPostProcess(this);
  55026. var index = camera._postProcesses.indexOf(this);
  55027. if (index === 0 && camera._postProcesses.length > 0) {
  55028. this._camera._postProcesses[0].markTextureDirty();
  55029. }
  55030. this.onActivateObservable.clear();
  55031. this.onAfterRenderObservable.clear();
  55032. this.onApplyObservable.clear();
  55033. this.onBeforeRenderObservable.clear();
  55034. this.onSizeChangedObservable.clear();
  55035. };
  55036. return PostProcess;
  55037. }());
  55038. BABYLON.PostProcess = PostProcess;
  55039. })(BABYLON || (BABYLON = {}));
  55040. //# sourceMappingURL=babylon.postProcess.js.map
  55041. var BABYLON;
  55042. (function (BABYLON) {
  55043. var PassPostProcess = /** @class */ (function (_super) {
  55044. __extends(PassPostProcess, _super);
  55045. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55046. if (camera === void 0) { camera = null; }
  55047. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55048. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55049. }
  55050. return PassPostProcess;
  55051. }(BABYLON.PostProcess));
  55052. BABYLON.PassPostProcess = PassPostProcess;
  55053. })(BABYLON || (BABYLON = {}));
  55054. //# sourceMappingURL=babylon.passPostProcess.js.map
  55055. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55056. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55057. s = arguments[i];
  55058. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55059. t[p] = s[p];
  55060. }
  55061. return t;
  55062. };
  55063. var BABYLON;
  55064. (function (BABYLON) {
  55065. var ShadowGenerator = /** @class */ (function () {
  55066. /**
  55067. * Creates a ShadowGenerator object.
  55068. * A ShadowGenerator is the required tool to use the shadows.
  55069. * Each light casting shadows needs to use its own ShadowGenerator.
  55070. * Required parameters :
  55071. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  55072. * - `light`: the light object generating the shadows.
  55073. * - `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.
  55074. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  55075. */
  55076. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  55077. // Members
  55078. this._bias = 0.00005;
  55079. this._blurBoxOffset = 1;
  55080. this._blurScale = 2;
  55081. this._blurKernel = 1;
  55082. this._useKernelBlur = false;
  55083. this._filter = ShadowGenerator.FILTER_NONE;
  55084. this._darkness = 0;
  55085. this._transparencyShadow = false;
  55086. /**
  55087. * Controls the extent to which the shadows fade out at the edge of the frustum
  55088. * Used only by directionals and spots
  55089. */
  55090. this.frustumEdgeFalloff = 0;
  55091. this.forceBackFacesOnly = false;
  55092. this._lightDirection = BABYLON.Vector3.Zero();
  55093. this._viewMatrix = BABYLON.Matrix.Zero();
  55094. this._projectionMatrix = BABYLON.Matrix.Zero();
  55095. this._transformMatrix = BABYLON.Matrix.Zero();
  55096. this._currentFaceIndex = 0;
  55097. this._currentFaceIndexCache = 0;
  55098. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  55099. this._mapSize = mapSize;
  55100. this._light = light;
  55101. this._scene = light.getScene();
  55102. light._shadowGenerator = this;
  55103. // Texture type fallback from float to int if not supported.
  55104. var caps = this._scene.getEngine().getCaps();
  55105. if (!useFullFloatFirst) {
  55106. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55107. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55108. }
  55109. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55110. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55111. }
  55112. else {
  55113. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55114. }
  55115. }
  55116. else {
  55117. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55118. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55119. }
  55120. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55121. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55122. }
  55123. else {
  55124. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55125. }
  55126. }
  55127. this._initializeGenerator();
  55128. }
  55129. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  55130. // Static
  55131. get: function () {
  55132. return ShadowGenerator._FILTER_NONE;
  55133. },
  55134. enumerable: true,
  55135. configurable: true
  55136. });
  55137. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  55138. get: function () {
  55139. return ShadowGenerator._FILTER_POISSONSAMPLING;
  55140. },
  55141. enumerable: true,
  55142. configurable: true
  55143. });
  55144. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  55145. get: function () {
  55146. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  55147. },
  55148. enumerable: true,
  55149. configurable: true
  55150. });
  55151. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  55152. get: function () {
  55153. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  55154. },
  55155. enumerable: true,
  55156. configurable: true
  55157. });
  55158. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  55159. get: function () {
  55160. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55161. },
  55162. enumerable: true,
  55163. configurable: true
  55164. });
  55165. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  55166. get: function () {
  55167. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55168. },
  55169. enumerable: true,
  55170. configurable: true
  55171. });
  55172. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  55173. get: function () {
  55174. return this._bias;
  55175. },
  55176. set: function (bias) {
  55177. this._bias = bias;
  55178. },
  55179. enumerable: true,
  55180. configurable: true
  55181. });
  55182. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55183. get: function () {
  55184. return this._blurBoxOffset;
  55185. },
  55186. set: function (value) {
  55187. if (this._blurBoxOffset === value) {
  55188. return;
  55189. }
  55190. this._blurBoxOffset = value;
  55191. this._disposeBlurPostProcesses();
  55192. },
  55193. enumerable: true,
  55194. configurable: true
  55195. });
  55196. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55197. get: function () {
  55198. return this._blurScale;
  55199. },
  55200. set: function (value) {
  55201. if (this._blurScale === value) {
  55202. return;
  55203. }
  55204. this._blurScale = value;
  55205. this._disposeBlurPostProcesses();
  55206. },
  55207. enumerable: true,
  55208. configurable: true
  55209. });
  55210. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55211. get: function () {
  55212. return this._blurKernel;
  55213. },
  55214. set: function (value) {
  55215. if (this._blurKernel === value) {
  55216. return;
  55217. }
  55218. this._blurKernel = value;
  55219. this._disposeBlurPostProcesses();
  55220. },
  55221. enumerable: true,
  55222. configurable: true
  55223. });
  55224. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55225. get: function () {
  55226. return this._useKernelBlur;
  55227. },
  55228. set: function (value) {
  55229. if (this._useKernelBlur === value) {
  55230. return;
  55231. }
  55232. this._useKernelBlur = value;
  55233. this._disposeBlurPostProcesses();
  55234. },
  55235. enumerable: true,
  55236. configurable: true
  55237. });
  55238. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55239. get: function () {
  55240. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55241. },
  55242. set: function (value) {
  55243. this._depthScale = value;
  55244. },
  55245. enumerable: true,
  55246. configurable: true
  55247. });
  55248. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55249. get: function () {
  55250. return this._filter;
  55251. },
  55252. set: function (value) {
  55253. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55254. if (this._light.needCube()) {
  55255. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55256. this.useExponentialShadowMap = true;
  55257. return;
  55258. }
  55259. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55260. this.useCloseExponentialShadowMap = true;
  55261. return;
  55262. }
  55263. }
  55264. if (this._filter === value) {
  55265. return;
  55266. }
  55267. this._filter = value;
  55268. this._disposeBlurPostProcesses();
  55269. this._applyFilterValues();
  55270. this._light._markMeshesAsLightDirty();
  55271. },
  55272. enumerable: true,
  55273. configurable: true
  55274. });
  55275. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55276. get: function () {
  55277. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55278. },
  55279. set: function (value) {
  55280. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55281. return;
  55282. }
  55283. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55284. },
  55285. enumerable: true,
  55286. configurable: true
  55287. });
  55288. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55289. get: function () {
  55290. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55291. return this.useExponentialShadowMap;
  55292. },
  55293. set: function (value) {
  55294. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55295. this.useExponentialShadowMap = value;
  55296. },
  55297. enumerable: true,
  55298. configurable: true
  55299. });
  55300. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55301. get: function () {
  55302. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55303. return this.useBlurExponentialShadowMap;
  55304. },
  55305. set: function (value) {
  55306. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55307. this.useBlurExponentialShadowMap = value;
  55308. },
  55309. enumerable: true,
  55310. configurable: true
  55311. });
  55312. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55313. get: function () {
  55314. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55315. },
  55316. set: function (value) {
  55317. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55318. return;
  55319. }
  55320. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55321. },
  55322. enumerable: true,
  55323. configurable: true
  55324. });
  55325. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55326. get: function () {
  55327. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55328. },
  55329. set: function (value) {
  55330. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55331. return;
  55332. }
  55333. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55334. },
  55335. enumerable: true,
  55336. configurable: true
  55337. });
  55338. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55339. get: function () {
  55340. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55341. },
  55342. set: function (value) {
  55343. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55344. return;
  55345. }
  55346. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55347. },
  55348. enumerable: true,
  55349. configurable: true
  55350. });
  55351. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55352. get: function () {
  55353. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55354. },
  55355. set: function (value) {
  55356. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55357. return;
  55358. }
  55359. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55360. },
  55361. enumerable: true,
  55362. configurable: true
  55363. });
  55364. /**
  55365. * Returns the darkness value (float).
  55366. */
  55367. ShadowGenerator.prototype.getDarkness = function () {
  55368. return this._darkness;
  55369. };
  55370. /**
  55371. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55372. * Returns the ShadowGenerator.
  55373. */
  55374. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55375. if (darkness >= 1.0)
  55376. this._darkness = 1.0;
  55377. else if (darkness <= 0.0)
  55378. this._darkness = 0.0;
  55379. else
  55380. this._darkness = darkness;
  55381. return this;
  55382. };
  55383. /**
  55384. * Sets the ability to have transparent shadow (boolean).
  55385. * Returns the ShadowGenerator.
  55386. */
  55387. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55388. this._transparencyShadow = hasShadow;
  55389. return this;
  55390. };
  55391. /**
  55392. * Returns a RenderTargetTexture object : the shadow map texture.
  55393. */
  55394. ShadowGenerator.prototype.getShadowMap = function () {
  55395. return this._shadowMap;
  55396. };
  55397. /**
  55398. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55399. */
  55400. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55401. if (this._shadowMap2) {
  55402. return this._shadowMap2;
  55403. }
  55404. return this._shadowMap;
  55405. };
  55406. /**
  55407. * Helper function to add a mesh and its descendants to the list of shadow casters
  55408. * @param mesh Mesh to add
  55409. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  55410. */
  55411. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  55412. if (includeDescendants === void 0) { includeDescendants = true; }
  55413. if (!this._shadowMap) {
  55414. return this;
  55415. }
  55416. if (!this._shadowMap.renderList) {
  55417. this._shadowMap.renderList = [];
  55418. }
  55419. this._shadowMap.renderList.push(mesh);
  55420. if (includeDescendants) {
  55421. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  55422. }
  55423. return this;
  55424. var _a;
  55425. };
  55426. /**
  55427. * Helper function to remove a mesh and its descendants from the list of shadow casters
  55428. * @param mesh Mesh to remove
  55429. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  55430. */
  55431. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  55432. if (includeDescendants === void 0) { includeDescendants = true; }
  55433. if (!this._shadowMap || !this._shadowMap.renderList) {
  55434. return this;
  55435. }
  55436. var index = this._shadowMap.renderList.indexOf(mesh);
  55437. if (index !== -1) {
  55438. this._shadowMap.renderList.splice(index, 1);
  55439. }
  55440. if (includeDescendants) {
  55441. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  55442. var child = _a[_i];
  55443. this.removeShadowCaster(child);
  55444. }
  55445. }
  55446. return this;
  55447. };
  55448. /**
  55449. * Returns the associated light object.
  55450. */
  55451. ShadowGenerator.prototype.getLight = function () {
  55452. return this._light;
  55453. };
  55454. ShadowGenerator.prototype._initializeGenerator = function () {
  55455. this._light._markMeshesAsLightDirty();
  55456. this._initializeShadowMap();
  55457. };
  55458. ShadowGenerator.prototype._initializeShadowMap = function () {
  55459. var _this = this;
  55460. // Render target
  55461. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  55462. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55463. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55464. this._shadowMap.anisotropicFilteringLevel = 1;
  55465. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55466. this._shadowMap.renderParticles = false;
  55467. this._shadowMap.ignoreCameraViewport = true;
  55468. // Record Face Index before render.
  55469. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  55470. _this._currentFaceIndex = faceIndex;
  55471. });
  55472. // Custom render function.
  55473. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  55474. // Blur if required afer render.
  55475. this._shadowMap.onAfterUnbindObservable.add(function () {
  55476. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  55477. return;
  55478. }
  55479. var shadowMap = _this.getShadowMapForRendering();
  55480. if (shadowMap) {
  55481. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  55482. }
  55483. });
  55484. // Clear according to the chosen filter.
  55485. this._shadowMap.onClearObservable.add(function (engine) {
  55486. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  55487. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  55488. }
  55489. else {
  55490. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55491. }
  55492. });
  55493. };
  55494. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  55495. var _this = this;
  55496. var engine = this._scene.getEngine();
  55497. var targetSize = this._mapSize / this.blurScale;
  55498. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  55499. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  55500. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55501. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55502. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55503. }
  55504. if (this.useKernelBlur) {
  55505. 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);
  55506. this._kernelBlurXPostprocess.width = targetSize;
  55507. this._kernelBlurXPostprocess.height = targetSize;
  55508. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  55509. effect.setTexture("textureSampler", _this._shadowMap);
  55510. });
  55511. 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);
  55512. this._kernelBlurXPostprocess.autoClear = false;
  55513. this._kernelBlurYPostprocess.autoClear = false;
  55514. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55515. this._kernelBlurXPostprocess.packedFloat = true;
  55516. this._kernelBlurYPostprocess.packedFloat = true;
  55517. }
  55518. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  55519. }
  55520. else {
  55521. 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);
  55522. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  55523. effect.setFloat2("screenSize", targetSize, targetSize);
  55524. effect.setTexture("textureSampler", _this._shadowMap);
  55525. });
  55526. this._boxBlurPostprocess.autoClear = false;
  55527. this._blurPostProcesses = [this._boxBlurPostprocess];
  55528. }
  55529. };
  55530. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55531. var index;
  55532. var engine = this._scene.getEngine();
  55533. if (depthOnlySubMeshes.length) {
  55534. engine.setColorWrite(false);
  55535. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55536. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  55537. }
  55538. engine.setColorWrite(true);
  55539. }
  55540. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55541. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  55542. }
  55543. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55544. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  55545. }
  55546. if (this._transparencyShadow) {
  55547. for (index = 0; index < transparentSubMeshes.length; index++) {
  55548. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  55549. }
  55550. }
  55551. };
  55552. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  55553. var _this = this;
  55554. var mesh = subMesh.getRenderingMesh();
  55555. var scene = this._scene;
  55556. var engine = scene.getEngine();
  55557. var material = subMesh.getMaterial();
  55558. if (!material) {
  55559. return;
  55560. }
  55561. // Culling
  55562. engine.setState(material.backFaceCulling);
  55563. // Managing instances
  55564. var batch = mesh._getInstancesRenderList(subMesh._id);
  55565. if (batch.mustReturn) {
  55566. return;
  55567. }
  55568. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  55569. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  55570. engine.enableEffect(this._effect);
  55571. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  55572. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  55573. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  55574. this._effect.setVector3("lightPosition", this.getLight().position);
  55575. if (scene.activeCamera) {
  55576. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  55577. }
  55578. // Alpha test
  55579. if (material && material.needAlphaTesting()) {
  55580. var alphaTexture = material.getAlphaTestTexture();
  55581. if (alphaTexture) {
  55582. this._effect.setTexture("diffuseSampler", alphaTexture);
  55583. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  55584. }
  55585. }
  55586. // Bones
  55587. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55588. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  55589. }
  55590. if (this.forceBackFacesOnly) {
  55591. engine.setState(true, 0, false, true);
  55592. }
  55593. // Draw
  55594. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55595. if (this.forceBackFacesOnly) {
  55596. engine.setState(true, 0, false, false);
  55597. }
  55598. }
  55599. else {
  55600. // Need to reset refresh rate of the shadowMap
  55601. if (this._shadowMap) {
  55602. this._shadowMap.resetRefreshCounter();
  55603. }
  55604. }
  55605. };
  55606. ShadowGenerator.prototype._applyFilterValues = function () {
  55607. if (!this._shadowMap) {
  55608. return;
  55609. }
  55610. if (this.filter === ShadowGenerator.FILTER_NONE) {
  55611. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  55612. }
  55613. else {
  55614. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55615. }
  55616. };
  55617. /**
  55618. * Force shader compilation including textures ready check
  55619. */
  55620. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  55621. var _this = this;
  55622. var localOptions = __assign({ useInstances: false }, options);
  55623. var shadowMap = this.getShadowMap();
  55624. if (!shadowMap) {
  55625. if (onCompiled) {
  55626. onCompiled(this);
  55627. }
  55628. return;
  55629. }
  55630. var renderList = shadowMap.renderList;
  55631. if (!renderList) {
  55632. if (onCompiled) {
  55633. onCompiled(this);
  55634. }
  55635. return;
  55636. }
  55637. var subMeshes = new Array();
  55638. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  55639. var mesh = renderList_1[_i];
  55640. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  55641. }
  55642. if (subMeshes.length === 0) {
  55643. if (onCompiled) {
  55644. onCompiled(this);
  55645. }
  55646. return;
  55647. }
  55648. var currentIndex = 0;
  55649. var checkReady = function () {
  55650. if (!_this._scene || !_this._scene.getEngine()) {
  55651. return;
  55652. }
  55653. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  55654. currentIndex++;
  55655. if (currentIndex >= subMeshes.length) {
  55656. if (onCompiled) {
  55657. onCompiled(_this);
  55658. }
  55659. return;
  55660. }
  55661. }
  55662. setTimeout(checkReady, 16);
  55663. };
  55664. checkReady();
  55665. };
  55666. /**
  55667. * Boolean : true when the ShadowGenerator is finally computed.
  55668. */
  55669. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  55670. var defines = [];
  55671. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55672. defines.push("#define FLOAT");
  55673. }
  55674. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55675. defines.push("#define ESM");
  55676. }
  55677. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55678. var mesh = subMesh.getMesh();
  55679. var material = subMesh.getMaterial();
  55680. // Alpha test
  55681. if (material && material.needAlphaTesting()) {
  55682. var alphaTexture = material.getAlphaTestTexture();
  55683. if (alphaTexture) {
  55684. defines.push("#define ALPHATEST");
  55685. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55686. attribs.push(BABYLON.VertexBuffer.UVKind);
  55687. defines.push("#define UV1");
  55688. }
  55689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55690. if (alphaTexture.coordinatesIndex === 1) {
  55691. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55692. defines.push("#define UV2");
  55693. }
  55694. }
  55695. }
  55696. }
  55697. // Bones
  55698. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55699. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55700. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55701. if (mesh.numBoneInfluencers > 4) {
  55702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55704. }
  55705. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55706. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55707. }
  55708. else {
  55709. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55710. }
  55711. // Instances
  55712. if (useInstances) {
  55713. defines.push("#define INSTANCES");
  55714. attribs.push("world0");
  55715. attribs.push("world1");
  55716. attribs.push("world2");
  55717. attribs.push("world3");
  55718. }
  55719. // Get correct effect
  55720. var join = defines.join("\n");
  55721. if (this._cachedDefines !== join) {
  55722. this._cachedDefines = join;
  55723. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  55724. }
  55725. if (!this._effect.isReady()) {
  55726. return false;
  55727. }
  55728. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55729. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  55730. this._initializeBlurRTTAndPostProcesses();
  55731. }
  55732. }
  55733. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  55734. return false;
  55735. }
  55736. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  55737. return false;
  55738. }
  55739. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  55740. return false;
  55741. }
  55742. return true;
  55743. };
  55744. /**
  55745. * This creates the defines related to the standard BJS materials.
  55746. */
  55747. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  55748. var scene = this._scene;
  55749. var light = this._light;
  55750. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55751. return;
  55752. }
  55753. defines["SHADOW" + lightIndex] = true;
  55754. if (this.usePoissonSampling) {
  55755. defines["SHADOWPCF" + lightIndex] = true;
  55756. }
  55757. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55758. defines["SHADOWESM" + lightIndex] = true;
  55759. }
  55760. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55761. defines["SHADOWCLOSEESM" + lightIndex] = true;
  55762. }
  55763. if (light.needCube()) {
  55764. defines["SHADOWCUBE" + lightIndex] = true;
  55765. }
  55766. };
  55767. /**
  55768. * This binds shadow lights related to the standard BJS materials.
  55769. * It implies the unifroms available on the materials are the standard BJS ones.
  55770. */
  55771. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  55772. var light = this._light;
  55773. var scene = this._scene;
  55774. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55775. return;
  55776. }
  55777. var camera = scene.activeCamera;
  55778. if (!camera) {
  55779. return;
  55780. }
  55781. var shadowMap = this.getShadowMap();
  55782. if (!shadowMap) {
  55783. return;
  55784. }
  55785. if (!light.needCube()) {
  55786. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  55787. }
  55788. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  55789. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  55790. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  55791. };
  55792. // Methods
  55793. /**
  55794. * Returns a Matrix object : the updated transformation matrix.
  55795. */
  55796. ShadowGenerator.prototype.getTransformMatrix = function () {
  55797. var scene = this._scene;
  55798. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  55799. return this._transformMatrix;
  55800. }
  55801. this._currentRenderID = scene.getRenderId();
  55802. this._currentFaceIndexCache = this._currentFaceIndex;
  55803. var lightPosition = this._light.position;
  55804. if (this._light.computeTransformedInformation()) {
  55805. lightPosition = this._light.transformedPosition;
  55806. }
  55807. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  55808. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  55809. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  55810. }
  55811. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  55812. this._cachedPosition = lightPosition.clone();
  55813. this._cachedDirection = this._lightDirection.clone();
  55814. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  55815. var shadowMap = this.getShadowMap();
  55816. if (shadowMap) {
  55817. var renderList = shadowMap.renderList;
  55818. if (renderList) {
  55819. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  55820. }
  55821. }
  55822. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  55823. }
  55824. return this._transformMatrix;
  55825. };
  55826. ShadowGenerator.prototype.recreateShadowMap = function () {
  55827. var shadowMap = this._shadowMap;
  55828. if (!shadowMap) {
  55829. return;
  55830. }
  55831. // Track render list.
  55832. var renderList = shadowMap.renderList;
  55833. // Clean up existing data.
  55834. this._disposeRTTandPostProcesses();
  55835. // Reinitializes.
  55836. this._initializeGenerator();
  55837. // Reaffect the filter to ensure a correct fallback if necessary.
  55838. this.filter = this.filter;
  55839. // Reaffect the filter.
  55840. this._applyFilterValues();
  55841. // Reaffect Render List.
  55842. this._shadowMap.renderList = renderList;
  55843. };
  55844. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  55845. if (this._shadowMap2) {
  55846. this._shadowMap2.dispose();
  55847. this._shadowMap2 = null;
  55848. }
  55849. if (this._boxBlurPostprocess) {
  55850. this._boxBlurPostprocess.dispose();
  55851. this._boxBlurPostprocess = null;
  55852. }
  55853. if (this._kernelBlurXPostprocess) {
  55854. this._kernelBlurXPostprocess.dispose();
  55855. this._kernelBlurXPostprocess = null;
  55856. }
  55857. if (this._kernelBlurYPostprocess) {
  55858. this._kernelBlurYPostprocess.dispose();
  55859. this._kernelBlurYPostprocess = null;
  55860. }
  55861. this._blurPostProcesses = [];
  55862. };
  55863. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  55864. if (this._shadowMap) {
  55865. this._shadowMap.dispose();
  55866. this._shadowMap = null;
  55867. }
  55868. this._disposeBlurPostProcesses();
  55869. };
  55870. /**
  55871. * Disposes the ShadowGenerator.
  55872. * Returns nothing.
  55873. */
  55874. ShadowGenerator.prototype.dispose = function () {
  55875. this._disposeRTTandPostProcesses();
  55876. if (this._light) {
  55877. this._light._shadowGenerator = null;
  55878. this._light._markMeshesAsLightDirty();
  55879. }
  55880. };
  55881. /**
  55882. * Serializes the ShadowGenerator and returns a serializationObject.
  55883. */
  55884. ShadowGenerator.prototype.serialize = function () {
  55885. var serializationObject = {};
  55886. var shadowMap = this.getShadowMap();
  55887. if (!shadowMap) {
  55888. return serializationObject;
  55889. }
  55890. serializationObject.lightId = this._light.id;
  55891. serializationObject.mapSize = shadowMap.getRenderSize();
  55892. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  55893. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  55894. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55895. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55896. serializationObject.usePoissonSampling = this.usePoissonSampling;
  55897. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  55898. serializationObject.depthScale = this.depthScale;
  55899. serializationObject.darkness = this.getDarkness();
  55900. serializationObject.blurBoxOffset = this.blurBoxOffset;
  55901. serializationObject.blurKernel = this.blurKernel;
  55902. serializationObject.blurScale = this.blurScale;
  55903. serializationObject.useKernelBlur = this.useKernelBlur;
  55904. serializationObject.transparencyShadow = this._transparencyShadow;
  55905. serializationObject.renderList = [];
  55906. if (shadowMap.renderList) {
  55907. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  55908. var mesh = shadowMap.renderList[meshIndex];
  55909. serializationObject.renderList.push(mesh.id);
  55910. }
  55911. }
  55912. return serializationObject;
  55913. };
  55914. /**
  55915. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  55916. */
  55917. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  55918. //casting to point light, as light is missing the position attr and typescript complains.
  55919. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  55920. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  55921. var shadowMap = shadowGenerator.getShadowMap();
  55922. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  55923. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  55924. meshes.forEach(function (mesh) {
  55925. if (!shadowMap) {
  55926. return;
  55927. }
  55928. if (!shadowMap.renderList) {
  55929. shadowMap.renderList = [];
  55930. }
  55931. shadowMap.renderList.push(mesh);
  55932. });
  55933. }
  55934. if (parsedShadowGenerator.usePoissonSampling) {
  55935. shadowGenerator.usePoissonSampling = true;
  55936. }
  55937. else if (parsedShadowGenerator.useExponentialShadowMap) {
  55938. shadowGenerator.useExponentialShadowMap = true;
  55939. }
  55940. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  55941. shadowGenerator.useBlurExponentialShadowMap = true;
  55942. }
  55943. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  55944. shadowGenerator.useCloseExponentialShadowMap = true;
  55945. }
  55946. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  55947. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  55948. }
  55949. else if (parsedShadowGenerator.useVarianceShadowMap) {
  55950. shadowGenerator.useExponentialShadowMap = true;
  55951. }
  55952. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  55953. shadowGenerator.useBlurExponentialShadowMap = true;
  55954. }
  55955. if (parsedShadowGenerator.depthScale) {
  55956. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  55957. }
  55958. if (parsedShadowGenerator.blurScale) {
  55959. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  55960. }
  55961. if (parsedShadowGenerator.blurBoxOffset) {
  55962. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  55963. }
  55964. if (parsedShadowGenerator.useKernelBlur) {
  55965. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  55966. }
  55967. if (parsedShadowGenerator.blurKernel) {
  55968. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  55969. }
  55970. if (parsedShadowGenerator.bias !== undefined) {
  55971. shadowGenerator.bias = parsedShadowGenerator.bias;
  55972. }
  55973. if (parsedShadowGenerator.darkness) {
  55974. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  55975. }
  55976. if (parsedShadowGenerator.transparencyShadow) {
  55977. shadowGenerator.setTransparencyShadow(true);
  55978. }
  55979. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  55980. return shadowGenerator;
  55981. };
  55982. ShadowGenerator._FILTER_NONE = 0;
  55983. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  55984. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  55985. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  55986. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  55987. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  55988. return ShadowGenerator;
  55989. }());
  55990. BABYLON.ShadowGenerator = ShadowGenerator;
  55991. })(BABYLON || (BABYLON = {}));
  55992. //# sourceMappingURL=babylon.shadowGenerator.js.map
  55993. var BABYLON;
  55994. (function (BABYLON) {
  55995. var DefaultLoadingScreen = /** @class */ (function () {
  55996. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  55997. if (_loadingText === void 0) { _loadingText = ""; }
  55998. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  55999. var _this = this;
  56000. this._renderingCanvas = _renderingCanvas;
  56001. this._loadingText = _loadingText;
  56002. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  56003. // Resize
  56004. this._resizeLoadingUI = function () {
  56005. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  56006. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  56007. if (!_this._loadingDiv) {
  56008. return;
  56009. }
  56010. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  56011. _this._loadingDiv.style.left = canvasRect.left + "px";
  56012. _this._loadingDiv.style.top = canvasRect.top + "px";
  56013. _this._loadingDiv.style.width = canvasRect.width + "px";
  56014. _this._loadingDiv.style.height = canvasRect.height + "px";
  56015. };
  56016. }
  56017. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  56018. if (this._loadingDiv) {
  56019. // Do not add a loading screen if there is already one
  56020. return;
  56021. }
  56022. this._loadingDiv = document.createElement("div");
  56023. this._loadingDiv.id = "babylonjsLoadingDiv";
  56024. this._loadingDiv.style.opacity = "0";
  56025. this._loadingDiv.style.transition = "opacity 1.5s ease";
  56026. this._loadingDiv.style.pointerEvents = "none";
  56027. // Loading text
  56028. this._loadingTextDiv = document.createElement("div");
  56029. this._loadingTextDiv.style.position = "absolute";
  56030. this._loadingTextDiv.style.left = "0";
  56031. this._loadingTextDiv.style.top = "50%";
  56032. this._loadingTextDiv.style.marginTop = "80px";
  56033. this._loadingTextDiv.style.width = "100%";
  56034. this._loadingTextDiv.style.height = "20px";
  56035. this._loadingTextDiv.style.fontFamily = "Arial";
  56036. this._loadingTextDiv.style.fontSize = "14px";
  56037. this._loadingTextDiv.style.color = "white";
  56038. this._loadingTextDiv.style.textAlign = "center";
  56039. this._loadingTextDiv.innerHTML = "Loading";
  56040. this._loadingDiv.appendChild(this._loadingTextDiv);
  56041. //set the predefined text
  56042. this._loadingTextDiv.innerHTML = this._loadingText;
  56043. // Generating keyframes
  56044. var style = document.createElement('style');
  56045. style.type = 'text/css';
  56046. 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 }";
  56047. style.innerHTML = keyFrames;
  56048. document.getElementsByTagName('head')[0].appendChild(style);
  56049. // Loading img
  56050. var imgBack = new Image();
  56051. 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";
  56052. imgBack.style.position = "absolute";
  56053. imgBack.style.left = "50%";
  56054. imgBack.style.top = "50%";
  56055. imgBack.style.marginLeft = "-60px";
  56056. imgBack.style.marginTop = "-60px";
  56057. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  56058. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  56059. imgBack.style.transformOrigin = "50% 50%";
  56060. imgBack.style.webkitTransformOrigin = "50% 50%";
  56061. this._loadingDiv.appendChild(imgBack);
  56062. this._resizeLoadingUI();
  56063. window.addEventListener("resize", this._resizeLoadingUI);
  56064. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56065. document.body.appendChild(this._loadingDiv);
  56066. this._loadingDiv.style.opacity = "1";
  56067. };
  56068. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  56069. var _this = this;
  56070. if (!this._loadingDiv) {
  56071. return;
  56072. }
  56073. var onTransitionEnd = function () {
  56074. if (!_this._loadingDiv) {
  56075. return;
  56076. }
  56077. document.body.removeChild(_this._loadingDiv);
  56078. window.removeEventListener("resize", _this._resizeLoadingUI);
  56079. _this._loadingDiv = null;
  56080. };
  56081. this._loadingDiv.style.opacity = "0";
  56082. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  56083. };
  56084. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  56085. set: function (text) {
  56086. this._loadingText = text;
  56087. if (this._loadingTextDiv) {
  56088. this._loadingTextDiv.innerHTML = this._loadingText;
  56089. }
  56090. },
  56091. enumerable: true,
  56092. configurable: true
  56093. });
  56094. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  56095. get: function () {
  56096. return this._loadingDivBackgroundColor;
  56097. },
  56098. set: function (color) {
  56099. this._loadingDivBackgroundColor = color;
  56100. if (!this._loadingDiv) {
  56101. return;
  56102. }
  56103. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56104. },
  56105. enumerable: true,
  56106. configurable: true
  56107. });
  56108. return DefaultLoadingScreen;
  56109. }());
  56110. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  56111. })(BABYLON || (BABYLON = {}));
  56112. //# sourceMappingURL=babylon.loadingScreen.js.map
  56113. var BABYLON;
  56114. (function (BABYLON) {
  56115. var SceneLoaderProgressEvent = /** @class */ (function () {
  56116. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  56117. this.lengthComputable = lengthComputable;
  56118. this.loaded = loaded;
  56119. this.total = total;
  56120. }
  56121. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  56122. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  56123. };
  56124. return SceneLoaderProgressEvent;
  56125. }());
  56126. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  56127. var SceneLoader = /** @class */ (function () {
  56128. function SceneLoader() {
  56129. }
  56130. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  56131. get: function () {
  56132. return 0;
  56133. },
  56134. enumerable: true,
  56135. configurable: true
  56136. });
  56137. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  56138. get: function () {
  56139. return 1;
  56140. },
  56141. enumerable: true,
  56142. configurable: true
  56143. });
  56144. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  56145. get: function () {
  56146. return 2;
  56147. },
  56148. enumerable: true,
  56149. configurable: true
  56150. });
  56151. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  56152. get: function () {
  56153. return 3;
  56154. },
  56155. enumerable: true,
  56156. configurable: true
  56157. });
  56158. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  56159. get: function () {
  56160. return SceneLoader._ForceFullSceneLoadingForIncremental;
  56161. },
  56162. set: function (value) {
  56163. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  56164. },
  56165. enumerable: true,
  56166. configurable: true
  56167. });
  56168. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  56169. get: function () {
  56170. return SceneLoader._ShowLoadingScreen;
  56171. },
  56172. set: function (value) {
  56173. SceneLoader._ShowLoadingScreen = value;
  56174. },
  56175. enumerable: true,
  56176. configurable: true
  56177. });
  56178. Object.defineProperty(SceneLoader, "loggingLevel", {
  56179. get: function () {
  56180. return SceneLoader._loggingLevel;
  56181. },
  56182. set: function (value) {
  56183. SceneLoader._loggingLevel = value;
  56184. },
  56185. enumerable: true,
  56186. configurable: true
  56187. });
  56188. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56189. get: function () {
  56190. return SceneLoader._CleanBoneMatrixWeights;
  56191. },
  56192. set: function (value) {
  56193. SceneLoader._CleanBoneMatrixWeights = value;
  56194. },
  56195. enumerable: true,
  56196. configurable: true
  56197. });
  56198. SceneLoader._getDefaultPlugin = function () {
  56199. return SceneLoader._registeredPlugins[".babylon"];
  56200. };
  56201. SceneLoader._getPluginForExtension = function (extension) {
  56202. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56203. if (registeredPlugin) {
  56204. return registeredPlugin;
  56205. }
  56206. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56207. return SceneLoader._getDefaultPlugin();
  56208. };
  56209. SceneLoader._getPluginForDirectLoad = function (data) {
  56210. for (var extension in SceneLoader._registeredPlugins) {
  56211. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56212. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56213. return SceneLoader._registeredPlugins[extension];
  56214. }
  56215. }
  56216. return SceneLoader._getDefaultPlugin();
  56217. };
  56218. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56219. if (sceneFilename.name) {
  56220. sceneFilename = sceneFilename.name;
  56221. }
  56222. var queryStringPosition = sceneFilename.indexOf("?");
  56223. if (queryStringPosition !== -1) {
  56224. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56225. }
  56226. var dotPosition = sceneFilename.lastIndexOf(".");
  56227. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56228. return SceneLoader._getPluginForExtension(extension);
  56229. };
  56230. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56231. SceneLoader._getDirectLoad = function (sceneFilename) {
  56232. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56233. return sceneFilename.substr(5);
  56234. }
  56235. return null;
  56236. };
  56237. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56238. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56239. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56240. var plugin;
  56241. if (registeredPlugin.plugin.createPlugin) {
  56242. plugin = registeredPlugin.plugin.createPlugin();
  56243. }
  56244. else {
  56245. plugin = registeredPlugin.plugin;
  56246. }
  56247. var useArrayBuffer = registeredPlugin.isBinary;
  56248. var database;
  56249. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56250. var dataCallback = function (data, responseURL) {
  56251. if (scene.isDisposed) {
  56252. onError("Scene has been disposed");
  56253. return;
  56254. }
  56255. scene.database = database;
  56256. onSuccess(plugin, data, responseURL);
  56257. };
  56258. var request = null;
  56259. var pluginDisposed = false;
  56260. var onDisposeObservable = plugin.onDisposeObservable;
  56261. if (onDisposeObservable) {
  56262. onDisposeObservable.add(function () {
  56263. pluginDisposed = true;
  56264. if (request) {
  56265. request.abort();
  56266. request = null;
  56267. }
  56268. onDispose();
  56269. });
  56270. }
  56271. var manifestChecked = function () {
  56272. if (pluginDisposed) {
  56273. return;
  56274. }
  56275. var url = rootUrl + sceneFilename;
  56276. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56277. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56278. } : undefined, database, useArrayBuffer, function (request, exception) {
  56279. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56280. });
  56281. };
  56282. if (directLoad) {
  56283. dataCallback(directLoad);
  56284. return plugin;
  56285. }
  56286. if (rootUrl.indexOf("file:") === -1) {
  56287. if (scene.getEngine().enableOfflineSupport) {
  56288. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56289. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56290. }
  56291. else {
  56292. manifestChecked();
  56293. }
  56294. }
  56295. else {
  56296. var fileOrString = sceneFilename;
  56297. if (fileOrString.name) {
  56298. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56299. }
  56300. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56301. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56302. }
  56303. else {
  56304. onError("Unable to find file named " + sceneFilename);
  56305. }
  56306. }
  56307. return plugin;
  56308. };
  56309. // Public functions
  56310. SceneLoader.GetPluginForExtension = function (extension) {
  56311. return SceneLoader._getPluginForExtension(extension).plugin;
  56312. };
  56313. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56314. return !!SceneLoader._registeredPlugins[extension];
  56315. };
  56316. SceneLoader.RegisterPlugin = function (plugin) {
  56317. if (typeof plugin.extensions === "string") {
  56318. var extension = plugin.extensions;
  56319. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56320. plugin: plugin,
  56321. isBinary: false
  56322. };
  56323. }
  56324. else {
  56325. var extensions = plugin.extensions;
  56326. Object.keys(extensions).forEach(function (extension) {
  56327. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56328. plugin: plugin,
  56329. isBinary: extensions[extension].isBinary
  56330. };
  56331. });
  56332. }
  56333. };
  56334. /**
  56335. * Import meshes into a scene
  56336. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56337. * @param rootUrl a string that defines the root url for scene and resources
  56338. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56339. * @param scene the instance of BABYLON.Scene to append to
  56340. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56341. * @param onProgress a callback with a progress event for each file being loaded
  56342. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56343. */
  56344. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56345. if (onSuccess === void 0) { onSuccess = null; }
  56346. if (onProgress === void 0) { onProgress = null; }
  56347. if (onError === void 0) { onError = null; }
  56348. if (pluginExtension === void 0) { pluginExtension = null; }
  56349. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56350. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56351. return null;
  56352. }
  56353. var loadingToken = {};
  56354. scene._addPendingData(loadingToken);
  56355. var disposeHandler = function () {
  56356. scene._removePendingData(loadingToken);
  56357. };
  56358. var errorHandler = function (message, exception) {
  56359. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56360. if (onError) {
  56361. onError(scene, errorMessage, exception);
  56362. }
  56363. else {
  56364. BABYLON.Tools.Error(errorMessage);
  56365. // should the exception be thrown?
  56366. }
  56367. disposeHandler();
  56368. };
  56369. var progressHandler = onProgress ? function (event) {
  56370. try {
  56371. onProgress(event);
  56372. }
  56373. catch (e) {
  56374. errorHandler("Error in onProgress callback", e);
  56375. }
  56376. } : undefined;
  56377. var successHandler = function (meshes, particleSystems, skeletons) {
  56378. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56379. if (onSuccess) {
  56380. try {
  56381. onSuccess(meshes, particleSystems, skeletons);
  56382. }
  56383. catch (e) {
  56384. errorHandler("Error in onSuccess callback", e);
  56385. }
  56386. }
  56387. scene._removePendingData(loadingToken);
  56388. };
  56389. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56390. if (plugin.rewriteRootURL) {
  56391. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56392. }
  56393. if (plugin.importMesh) {
  56394. var syncedPlugin = plugin;
  56395. var meshes = new Array();
  56396. var particleSystems = new Array();
  56397. var skeletons = new Array();
  56398. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56399. return;
  56400. }
  56401. scene.loadingPluginName = plugin.name;
  56402. successHandler(meshes, particleSystems, skeletons);
  56403. }
  56404. else {
  56405. var asyncedPlugin = plugin;
  56406. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56407. scene.loadingPluginName = plugin.name;
  56408. successHandler(meshes, particleSystems, skeletons);
  56409. }, progressHandler, errorHandler);
  56410. }
  56411. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56412. };
  56413. /**
  56414. * Load a scene
  56415. * @param rootUrl a string that defines the root url for scene and resources
  56416. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56417. * @param engine is the instance of BABYLON.Engine to use to create the scene
  56418. * @param onSuccess a callback with the scene when import succeeds
  56419. * @param onProgress a callback with a progress event for each file being loaded
  56420. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56421. */
  56422. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  56423. if (onSuccess === void 0) { onSuccess = null; }
  56424. if (onProgress === void 0) { onProgress = null; }
  56425. if (onError === void 0) { onError = null; }
  56426. if (pluginExtension === void 0) { pluginExtension = null; }
  56427. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  56428. };
  56429. /**
  56430. * Append a scene
  56431. * @param rootUrl a string that defines the root url for scene and resources
  56432. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56433. * @param scene is the instance of BABYLON.Scene to append to
  56434. * @param onSuccess a callback with the scene when import succeeds
  56435. * @param onProgress a callback with a progress event for each file being loaded
  56436. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56437. */
  56438. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56439. if (onSuccess === void 0) { onSuccess = null; }
  56440. if (onProgress === void 0) { onProgress = null; }
  56441. if (onError === void 0) { onError = null; }
  56442. if (pluginExtension === void 0) { pluginExtension = null; }
  56443. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56444. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56445. return null;
  56446. }
  56447. if (SceneLoader.ShowLoadingScreen) {
  56448. scene.getEngine().displayLoadingUI();
  56449. }
  56450. var loadingToken = {};
  56451. scene._addPendingData(loadingToken);
  56452. var disposeHandler = function () {
  56453. scene._removePendingData(loadingToken);
  56454. scene.getEngine().hideLoadingUI();
  56455. };
  56456. var errorHandler = function (message, exception) {
  56457. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56458. if (onError) {
  56459. onError(scene, errorMessage, exception);
  56460. }
  56461. else {
  56462. BABYLON.Tools.Error(errorMessage);
  56463. // should the exception be thrown?
  56464. }
  56465. disposeHandler();
  56466. };
  56467. var progressHandler = onProgress ? function (event) {
  56468. try {
  56469. onProgress(event);
  56470. }
  56471. catch (e) {
  56472. errorHandler("Error in onProgress callback", e);
  56473. }
  56474. } : undefined;
  56475. var successHandler = function () {
  56476. if (onSuccess) {
  56477. try {
  56478. onSuccess(scene);
  56479. }
  56480. catch (e) {
  56481. errorHandler("Error in onSuccess callback", e);
  56482. }
  56483. }
  56484. scene._removePendingData(loadingToken);
  56485. };
  56486. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56487. if (plugin.load) {
  56488. var syncedPlugin = plugin;
  56489. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  56490. return;
  56491. }
  56492. scene.loadingPluginName = plugin.name;
  56493. successHandler();
  56494. }
  56495. else {
  56496. var asyncedPlugin = plugin;
  56497. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  56498. scene.loadingPluginName = plugin.name;
  56499. successHandler();
  56500. }, progressHandler, errorHandler);
  56501. }
  56502. if (SceneLoader.ShowLoadingScreen) {
  56503. scene.executeWhenReady(function () {
  56504. scene.getEngine().hideLoadingUI();
  56505. });
  56506. }
  56507. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56508. };
  56509. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56510. if (onSuccess === void 0) { onSuccess = null; }
  56511. if (onProgress === void 0) { onProgress = null; }
  56512. if (onError === void 0) { onError = null; }
  56513. if (pluginExtension === void 0) { pluginExtension = null; }
  56514. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56515. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56516. return null;
  56517. }
  56518. var loadingToken = {};
  56519. scene._addPendingData(loadingToken);
  56520. var disposeHandler = function () {
  56521. scene._removePendingData(loadingToken);
  56522. };
  56523. var errorHandler = function (message, exception) {
  56524. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56525. if (onError) {
  56526. onError(scene, errorMessage, exception);
  56527. }
  56528. else {
  56529. BABYLON.Tools.Error(errorMessage);
  56530. // should the exception be thrown?
  56531. }
  56532. disposeHandler();
  56533. };
  56534. var progressHandler = onProgress ? function (event) {
  56535. try {
  56536. onProgress(event);
  56537. }
  56538. catch (e) {
  56539. errorHandler("Error in onProgress callback", e);
  56540. }
  56541. } : undefined;
  56542. var successHandler = function (assets) {
  56543. if (onSuccess) {
  56544. try {
  56545. onSuccess(assets);
  56546. }
  56547. catch (e) {
  56548. errorHandler("Error in onSuccess callback", e);
  56549. }
  56550. }
  56551. scene._removePendingData(loadingToken);
  56552. };
  56553. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56554. if (plugin.loadAssets) {
  56555. var syncedPlugin = plugin;
  56556. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  56557. if (!assetContainer) {
  56558. return;
  56559. }
  56560. scene.loadingPluginName = plugin.name;
  56561. successHandler(assetContainer);
  56562. }
  56563. else if (plugin.loadAssetsAsync) {
  56564. var asyncedPlugin = plugin;
  56565. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  56566. if (assetContainer) {
  56567. scene.loadingPluginName = plugin.name;
  56568. successHandler(assetContainer);
  56569. }
  56570. }, progressHandler, errorHandler);
  56571. }
  56572. else {
  56573. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  56574. }
  56575. if (SceneLoader.ShowLoadingScreen) {
  56576. scene.executeWhenReady(function () {
  56577. scene.getEngine().hideLoadingUI();
  56578. });
  56579. }
  56580. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56581. };
  56582. // Flags
  56583. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  56584. SceneLoader._ShowLoadingScreen = true;
  56585. SceneLoader._CleanBoneMatrixWeights = false;
  56586. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  56587. // Members
  56588. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  56589. SceneLoader._registeredPlugins = {};
  56590. return SceneLoader;
  56591. }());
  56592. BABYLON.SceneLoader = SceneLoader;
  56593. ;
  56594. })(BABYLON || (BABYLON = {}));
  56595. //# sourceMappingURL=babylon.sceneLoader.js.map
  56596. var BABYLON;
  56597. (function (BABYLON) {
  56598. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  56599. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56600. var parsedMaterial = parsedData.materials[index];
  56601. if (parsedMaterial.id === id) {
  56602. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56603. }
  56604. }
  56605. return null;
  56606. };
  56607. var isDescendantOf = function (mesh, names, hierarchyIds) {
  56608. for (var i in names) {
  56609. if (mesh.name === names[i]) {
  56610. hierarchyIds.push(mesh.id);
  56611. return true;
  56612. }
  56613. }
  56614. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  56615. hierarchyIds.push(mesh.id);
  56616. return true;
  56617. }
  56618. return false;
  56619. };
  56620. var logOperation = function (operation, producer) {
  56621. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  56622. };
  56623. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  56624. if (addToScene === void 0) { addToScene = false; }
  56625. var container = new BABYLON.AssetContainer(scene);
  56626. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56627. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56628. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56629. // and avoid problems with multiple concurrent .babylon loads.
  56630. var log = "importScene has failed JSON parse";
  56631. try {
  56632. var parsedData = JSON.parse(data);
  56633. log = "";
  56634. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56635. var index;
  56636. var cache;
  56637. // Lights
  56638. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  56639. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  56640. var parsedLight = parsedData.lights[index];
  56641. var light = BABYLON.Light.Parse(parsedLight, scene);
  56642. if (light) {
  56643. container.lights.push(light);
  56644. log += (index === 0 ? "\n\tLights:" : "");
  56645. log += "\n\t\t" + light.toString(fullDetails);
  56646. }
  56647. }
  56648. }
  56649. // Animations
  56650. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  56651. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  56652. var parsedAnimation = parsedData.animations[index];
  56653. var animation = BABYLON.Animation.Parse(parsedAnimation);
  56654. scene.animations.push(animation);
  56655. container.animations.push(animation);
  56656. log += (index === 0 ? "\n\tAnimations:" : "");
  56657. log += "\n\t\t" + animation.toString(fullDetails);
  56658. }
  56659. }
  56660. // Materials
  56661. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  56662. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56663. var parsedMaterial = parsedData.materials[index];
  56664. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56665. container.materials.push(mat);
  56666. log += (index === 0 ? "\n\tMaterials:" : "");
  56667. log += "\n\t\t" + mat.toString(fullDetails);
  56668. }
  56669. }
  56670. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56671. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  56672. var parsedMultiMaterial = parsedData.multiMaterials[index];
  56673. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56674. container.multiMaterials.push(mmat);
  56675. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  56676. log += "\n\t\t" + mmat.toString(fullDetails);
  56677. }
  56678. }
  56679. // Morph targets
  56680. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  56681. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  56682. var managerData = _a[_i];
  56683. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  56684. }
  56685. }
  56686. // Skeletons
  56687. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  56688. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  56689. var parsedSkeleton = parsedData.skeletons[index];
  56690. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  56691. container.skeletons.push(skeleton);
  56692. log += (index === 0 ? "\n\tSkeletons:" : "");
  56693. log += "\n\t\t" + skeleton.toString(fullDetails);
  56694. }
  56695. }
  56696. // Geometries
  56697. var geometries = parsedData.geometries;
  56698. if (geometries !== undefined && geometries !== null) {
  56699. var addedGeometry = new Array();
  56700. // Boxes
  56701. var boxes = geometries.boxes;
  56702. if (boxes !== undefined && boxes !== null) {
  56703. for (index = 0, cache = boxes.length; index < cache; index++) {
  56704. var parsedBox = boxes[index];
  56705. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  56706. }
  56707. }
  56708. // Spheres
  56709. var spheres = geometries.spheres;
  56710. if (spheres !== undefined && spheres !== null) {
  56711. for (index = 0, cache = spheres.length; index < cache; index++) {
  56712. var parsedSphere = spheres[index];
  56713. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  56714. }
  56715. }
  56716. // Cylinders
  56717. var cylinders = geometries.cylinders;
  56718. if (cylinders !== undefined && cylinders !== null) {
  56719. for (index = 0, cache = cylinders.length; index < cache; index++) {
  56720. var parsedCylinder = cylinders[index];
  56721. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  56722. }
  56723. }
  56724. // Toruses
  56725. var toruses = geometries.toruses;
  56726. if (toruses !== undefined && toruses !== null) {
  56727. for (index = 0, cache = toruses.length; index < cache; index++) {
  56728. var parsedTorus = toruses[index];
  56729. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  56730. }
  56731. }
  56732. // Grounds
  56733. var grounds = geometries.grounds;
  56734. if (grounds !== undefined && grounds !== null) {
  56735. for (index = 0, cache = grounds.length; index < cache; index++) {
  56736. var parsedGround = grounds[index];
  56737. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  56738. }
  56739. }
  56740. // Planes
  56741. var planes = geometries.planes;
  56742. if (planes !== undefined && planes !== null) {
  56743. for (index = 0, cache = planes.length; index < cache; index++) {
  56744. var parsedPlane = planes[index];
  56745. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  56746. }
  56747. }
  56748. // TorusKnots
  56749. var torusKnots = geometries.torusKnots;
  56750. if (torusKnots !== undefined && torusKnots !== null) {
  56751. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  56752. var parsedTorusKnot = torusKnots[index];
  56753. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  56754. }
  56755. }
  56756. // VertexData
  56757. var vertexData = geometries.vertexData;
  56758. if (vertexData !== undefined && vertexData !== null) {
  56759. for (index = 0, cache = vertexData.length; index < cache; index++) {
  56760. var parsedVertexData = vertexData[index];
  56761. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  56762. }
  56763. }
  56764. addedGeometry.forEach(function (g) {
  56765. if (g) {
  56766. container.geometries.push(g);
  56767. }
  56768. });
  56769. }
  56770. // Transform nodes
  56771. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  56772. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  56773. var parsedTransformNode = parsedData.transformNodes[index];
  56774. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  56775. container.transformNodes.push(node);
  56776. }
  56777. }
  56778. // Meshes
  56779. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56780. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56781. var parsedMesh = parsedData.meshes[index];
  56782. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  56783. container.meshes.push(mesh);
  56784. log += (index === 0 ? "\n\tMeshes:" : "");
  56785. log += "\n\t\t" + mesh.toString(fullDetails);
  56786. }
  56787. }
  56788. // Cameras
  56789. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  56790. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  56791. var parsedCamera = parsedData.cameras[index];
  56792. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  56793. container.cameras.push(camera);
  56794. log += (index === 0 ? "\n\tCameras:" : "");
  56795. log += "\n\t\t" + camera.toString(fullDetails);
  56796. }
  56797. }
  56798. // Browsing all the graph to connect the dots
  56799. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  56800. var camera = scene.cameras[index];
  56801. if (camera._waitingParentId) {
  56802. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  56803. camera._waitingParentId = null;
  56804. }
  56805. }
  56806. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56807. var light_1 = scene.lights[index];
  56808. if (light_1 && light_1._waitingParentId) {
  56809. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  56810. light_1._waitingParentId = null;
  56811. }
  56812. }
  56813. // Sounds
  56814. // TODO: add sound
  56815. var loadedSounds = [];
  56816. var loadedSound;
  56817. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  56818. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  56819. var parsedSound = parsedData.sounds[index];
  56820. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56821. if (!parsedSound.url)
  56822. parsedSound.url = parsedSound.name;
  56823. if (!loadedSounds[parsedSound.url]) {
  56824. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  56825. loadedSounds[parsedSound.url] = loadedSound;
  56826. container.sounds.push(loadedSound);
  56827. }
  56828. else {
  56829. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  56830. }
  56831. }
  56832. else {
  56833. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  56834. }
  56835. }
  56836. }
  56837. loadedSounds = [];
  56838. // Connect parents & children and parse actions
  56839. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  56840. var transformNode = scene.transformNodes[index];
  56841. if (transformNode._waitingParentId) {
  56842. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  56843. transformNode._waitingParentId = null;
  56844. }
  56845. }
  56846. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56847. var mesh = scene.meshes[index];
  56848. if (mesh._waitingParentId) {
  56849. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  56850. mesh._waitingParentId = null;
  56851. }
  56852. if (mesh._waitingActions) {
  56853. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  56854. mesh._waitingActions = null;
  56855. }
  56856. }
  56857. // freeze world matrix application
  56858. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56859. var currentMesh = scene.meshes[index];
  56860. if (currentMesh._waitingFreezeWorldMatrix) {
  56861. currentMesh.freezeWorldMatrix();
  56862. currentMesh._waitingFreezeWorldMatrix = null;
  56863. }
  56864. else {
  56865. currentMesh.computeWorldMatrix(true);
  56866. }
  56867. }
  56868. // Particles Systems
  56869. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56870. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56871. var parsedParticleSystem = parsedData.particleSystems[index];
  56872. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56873. container.particleSystems.push(ps);
  56874. }
  56875. }
  56876. // Lens flares
  56877. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  56878. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  56879. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  56880. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  56881. container.lensFlareSystems.push(lf);
  56882. }
  56883. }
  56884. // Shadows
  56885. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  56886. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  56887. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  56888. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  56889. container.shadowGenerators.push(sg);
  56890. }
  56891. }
  56892. // Lights exclusions / inclusions
  56893. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56894. var light_2 = scene.lights[index];
  56895. // Excluded check
  56896. if (light_2._excludedMeshesIds.length > 0) {
  56897. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  56898. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  56899. if (excludedMesh) {
  56900. light_2.excludedMeshes.push(excludedMesh);
  56901. }
  56902. }
  56903. light_2._excludedMeshesIds = [];
  56904. }
  56905. // Included check
  56906. if (light_2._includedOnlyMeshesIds.length > 0) {
  56907. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  56908. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  56909. if (includedOnlyMesh) {
  56910. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  56911. }
  56912. }
  56913. light_2._includedOnlyMeshesIds = [];
  56914. }
  56915. }
  56916. // Actions (scene)
  56917. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  56918. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  56919. }
  56920. if (!addToScene) {
  56921. container.removeAllFromScene();
  56922. }
  56923. return container;
  56924. }
  56925. catch (err) {
  56926. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  56927. if (onError) {
  56928. onError(msg, err);
  56929. }
  56930. else {
  56931. BABYLON.Tools.Log(msg);
  56932. throw err;
  56933. }
  56934. }
  56935. finally {
  56936. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  56937. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  56938. }
  56939. }
  56940. return null;
  56941. };
  56942. BABYLON.SceneLoader.RegisterPlugin({
  56943. name: "babylon.js",
  56944. extensions: ".babylon",
  56945. canDirectLoad: function (data) {
  56946. if (data.indexOf("babylon") !== -1) {
  56947. return true;
  56948. }
  56949. return false;
  56950. },
  56951. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  56952. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56953. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56954. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56955. // and avoid problems with multiple concurrent .babylon loads.
  56956. var log = "importMesh has failed JSON parse";
  56957. try {
  56958. var parsedData = JSON.parse(data);
  56959. log = "";
  56960. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56961. if (!meshesNames) {
  56962. meshesNames = null;
  56963. }
  56964. else if (!Array.isArray(meshesNames)) {
  56965. meshesNames = [meshesNames];
  56966. }
  56967. var hierarchyIds = new Array();
  56968. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56969. var loadedSkeletonsIds = [];
  56970. var loadedMaterialsIds = [];
  56971. var index;
  56972. var cache;
  56973. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56974. var parsedMesh = parsedData.meshes[index];
  56975. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  56976. if (meshesNames !== null) {
  56977. // Remove found mesh name from list.
  56978. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  56979. }
  56980. //Geometry?
  56981. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  56982. //does the file contain geometries?
  56983. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  56984. //find the correct geometry and add it to the scene
  56985. var found = false;
  56986. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  56987. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  56988. return;
  56989. }
  56990. else {
  56991. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  56992. if (parsedGeometryData.id === parsedMesh.geometryId) {
  56993. switch (geometryType) {
  56994. case "boxes":
  56995. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  56996. break;
  56997. case "spheres":
  56998. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  56999. break;
  57000. case "cylinders":
  57001. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  57002. break;
  57003. case "toruses":
  57004. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  57005. break;
  57006. case "grounds":
  57007. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  57008. break;
  57009. case "planes":
  57010. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  57011. break;
  57012. case "torusKnots":
  57013. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  57014. break;
  57015. case "vertexData":
  57016. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  57017. break;
  57018. }
  57019. found = true;
  57020. }
  57021. });
  57022. }
  57023. });
  57024. if (found === false) {
  57025. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  57026. }
  57027. }
  57028. }
  57029. // Material ?
  57030. if (parsedMesh.materialId) {
  57031. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  57032. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57033. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  57034. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  57035. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  57036. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  57037. var subMatId = parsedMultiMaterial.materials[matIndex];
  57038. loadedMaterialsIds.push(subMatId);
  57039. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  57040. log += "\n\tMaterial " + mat.toString(fullDetails);
  57041. }
  57042. loadedMaterialsIds.push(parsedMultiMaterial.id);
  57043. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57044. materialFound = true;
  57045. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  57046. break;
  57047. }
  57048. }
  57049. }
  57050. if (materialFound === false) {
  57051. loadedMaterialsIds.push(parsedMesh.materialId);
  57052. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  57053. if (!mat) {
  57054. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  57055. }
  57056. else {
  57057. log += "\n\tMaterial " + mat.toString(fullDetails);
  57058. }
  57059. }
  57060. }
  57061. // Skeleton ?
  57062. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57063. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  57064. if (skeletonAlreadyLoaded === false) {
  57065. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  57066. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  57067. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  57068. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57069. skeletons.push(skeleton);
  57070. loadedSkeletonsIds.push(parsedSkeleton.id);
  57071. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  57072. }
  57073. }
  57074. }
  57075. }
  57076. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57077. meshes.push(mesh);
  57078. log += "\n\tMesh " + mesh.toString(fullDetails);
  57079. }
  57080. }
  57081. // Connecting parents
  57082. var currentMesh;
  57083. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57084. currentMesh = scene.meshes[index];
  57085. if (currentMesh._waitingParentId) {
  57086. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  57087. currentMesh._waitingParentId = null;
  57088. }
  57089. }
  57090. // freeze and compute world matrix application
  57091. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57092. currentMesh = scene.meshes[index];
  57093. if (currentMesh._waitingFreezeWorldMatrix) {
  57094. currentMesh.freezeWorldMatrix();
  57095. currentMesh._waitingFreezeWorldMatrix = null;
  57096. }
  57097. else {
  57098. currentMesh.computeWorldMatrix(true);
  57099. }
  57100. }
  57101. }
  57102. // Particles
  57103. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57104. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57105. var parsedParticleSystem = parsedData.particleSystems[index];
  57106. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  57107. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  57108. }
  57109. }
  57110. }
  57111. return true;
  57112. }
  57113. catch (err) {
  57114. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  57115. if (onError) {
  57116. onError(msg, err);
  57117. }
  57118. else {
  57119. BABYLON.Tools.Log(msg);
  57120. throw err;
  57121. }
  57122. }
  57123. finally {
  57124. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57125. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57126. }
  57127. }
  57128. return false;
  57129. },
  57130. load: function (scene, data, rootUrl, onError) {
  57131. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57132. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57133. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57134. // and avoid problems with multiple concurrent .babylon loads.
  57135. var log = "importScene has failed JSON parse";
  57136. try {
  57137. var parsedData = JSON.parse(data);
  57138. log = "";
  57139. // Scene
  57140. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  57141. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  57142. }
  57143. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  57144. scene.autoClear = parsedData.autoClear;
  57145. }
  57146. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  57147. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  57148. }
  57149. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  57150. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  57151. }
  57152. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  57153. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  57154. }
  57155. // Fog
  57156. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  57157. scene.fogMode = parsedData.fogMode;
  57158. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  57159. scene.fogStart = parsedData.fogStart;
  57160. scene.fogEnd = parsedData.fogEnd;
  57161. scene.fogDensity = parsedData.fogDensity;
  57162. log += "\tFog mode for scene: ";
  57163. switch (scene.fogMode) {
  57164. // getters not compiling, so using hardcoded
  57165. case 1:
  57166. log += "exp\n";
  57167. break;
  57168. case 2:
  57169. log += "exp2\n";
  57170. break;
  57171. case 3:
  57172. log += "linear\n";
  57173. break;
  57174. }
  57175. }
  57176. //Physics
  57177. if (parsedData.physicsEnabled) {
  57178. var physicsPlugin;
  57179. if (parsedData.physicsEngine === "cannon") {
  57180. physicsPlugin = new BABYLON.CannonJSPlugin();
  57181. }
  57182. else if (parsedData.physicsEngine === "oimo") {
  57183. physicsPlugin = new BABYLON.OimoJSPlugin();
  57184. }
  57185. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57186. //else - default engine, which is currently oimo
  57187. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57188. scene.enablePhysics(physicsGravity, physicsPlugin);
  57189. }
  57190. // Metadata
  57191. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57192. scene.metadata = parsedData.metadata;
  57193. }
  57194. //collisions, if defined. otherwise, default is true
  57195. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57196. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57197. }
  57198. scene.workerCollisions = !!parsedData.workerCollisions;
  57199. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57200. if (!container) {
  57201. return false;
  57202. }
  57203. if (parsedData.autoAnimate) {
  57204. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57205. }
  57206. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57207. scene.setActiveCameraByID(parsedData.activeCameraID);
  57208. }
  57209. // Environment texture
  57210. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57211. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57212. if (parsedData.createDefaultSkybox === true) {
  57213. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57214. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57215. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57216. }
  57217. }
  57218. // Finish
  57219. return true;
  57220. }
  57221. catch (err) {
  57222. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57223. if (onError) {
  57224. onError(msg, err);
  57225. }
  57226. else {
  57227. BABYLON.Tools.Log(msg);
  57228. throw err;
  57229. }
  57230. }
  57231. finally {
  57232. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57233. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57234. }
  57235. }
  57236. return false;
  57237. },
  57238. loadAssets: function (scene, data, rootUrl, onError) {
  57239. var container = loadAssets(scene, data, rootUrl, onerror);
  57240. return container;
  57241. }
  57242. });
  57243. })(BABYLON || (BABYLON = {}));
  57244. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57245. var BABYLON;
  57246. (function (BABYLON) {
  57247. var FilesInput = /** @class */ (function () {
  57248. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57249. this.onProcessFileCallback = function () { return true; };
  57250. this._engine = engine;
  57251. this._currentScene = scene;
  57252. this._sceneLoadedCallback = sceneLoadedCallback;
  57253. this._progressCallback = progressCallback;
  57254. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57255. this._textureLoadingCallback = textureLoadingCallback;
  57256. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57257. this._onReloadCallback = onReloadCallback;
  57258. this._errorCallback = errorCallback;
  57259. }
  57260. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57261. var _this = this;
  57262. if (elementToMonitor) {
  57263. this._elementToMonitor = elementToMonitor;
  57264. this._dragEnterHandler = function (e) { _this.drag(e); };
  57265. this._dragOverHandler = function (e) { _this.drag(e); };
  57266. this._dropHandler = function (e) { _this.drop(e); };
  57267. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57268. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57269. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57270. }
  57271. };
  57272. FilesInput.prototype.dispose = function () {
  57273. if (!this._elementToMonitor) {
  57274. return;
  57275. }
  57276. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57277. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57278. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57279. };
  57280. FilesInput.prototype.renderFunction = function () {
  57281. if (this._additionalRenderLoopLogicCallback) {
  57282. this._additionalRenderLoopLogicCallback();
  57283. }
  57284. if (this._currentScene) {
  57285. if (this._textureLoadingCallback) {
  57286. var remaining = this._currentScene.getWaitingItemsCount();
  57287. if (remaining > 0) {
  57288. this._textureLoadingCallback(remaining);
  57289. }
  57290. }
  57291. this._currentScene.render();
  57292. }
  57293. };
  57294. FilesInput.prototype.drag = function (e) {
  57295. e.stopPropagation();
  57296. e.preventDefault();
  57297. };
  57298. FilesInput.prototype.drop = function (eventDrop) {
  57299. eventDrop.stopPropagation();
  57300. eventDrop.preventDefault();
  57301. this.loadFiles(eventDrop);
  57302. };
  57303. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57304. var _this = this;
  57305. var reader = folder.createReader();
  57306. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57307. reader.readEntries(function (entries) {
  57308. remaining.count += entries.length;
  57309. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57310. var entry = entries_1[_i];
  57311. if (entry.isFile) {
  57312. entry.file(function (file) {
  57313. file.correctName = relativePath + file.name;
  57314. files.push(file);
  57315. if (--remaining.count === 0) {
  57316. callback();
  57317. }
  57318. });
  57319. }
  57320. else if (entry.isDirectory) {
  57321. _this._traverseFolder(entry, files, remaining, callback);
  57322. }
  57323. }
  57324. if (--remaining.count) {
  57325. callback();
  57326. }
  57327. });
  57328. };
  57329. FilesInput.prototype._processFiles = function (files) {
  57330. for (var i = 0; i < files.length; i++) {
  57331. var name = files[i].correctName.toLowerCase();
  57332. var extension = name.split('.').pop();
  57333. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57334. continue;
  57335. }
  57336. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57337. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57338. this._sceneFileToLoad = files[i];
  57339. }
  57340. else {
  57341. FilesInput.FilesToLoad[name] = files[i];
  57342. }
  57343. }
  57344. };
  57345. FilesInput.prototype.loadFiles = function (event) {
  57346. var _this = this;
  57347. if (this._startingProcessingFilesCallback)
  57348. this._startingProcessingFilesCallback();
  57349. // Handling data transfer via drag'n'drop
  57350. if (event && event.dataTransfer && event.dataTransfer.files) {
  57351. this._filesToLoad = event.dataTransfer.files;
  57352. }
  57353. // Handling files from input files
  57354. if (event && event.target && event.target.files) {
  57355. this._filesToLoad = event.target.files;
  57356. }
  57357. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57358. var files_1 = new Array();
  57359. var folders = [];
  57360. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57361. for (var i = 0; i < this._filesToLoad.length; i++) {
  57362. var fileToLoad = this._filesToLoad[i];
  57363. var name_1 = fileToLoad.name.toLowerCase();
  57364. var entry = void 0;
  57365. fileToLoad.correctName = name_1;
  57366. if (items) {
  57367. var item = items[i];
  57368. if (item.getAsEntry) {
  57369. entry = item.getAsEntry();
  57370. }
  57371. else if (item.webkitGetAsEntry) {
  57372. entry = item.webkitGetAsEntry();
  57373. }
  57374. }
  57375. if (!entry) {
  57376. files_1.push(fileToLoad);
  57377. }
  57378. else {
  57379. if (entry.isDirectory) {
  57380. folders.push(entry);
  57381. }
  57382. else {
  57383. files_1.push(fileToLoad);
  57384. }
  57385. }
  57386. }
  57387. if (folders.length === 0) {
  57388. this._processFiles(files_1);
  57389. this._processReload();
  57390. }
  57391. else {
  57392. var remaining = { count: folders.length };
  57393. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57394. var folder = folders_1[_i];
  57395. this._traverseFolder(folder, files_1, remaining, function () {
  57396. _this._processFiles(files_1);
  57397. if (remaining.count === 0) {
  57398. _this._processReload();
  57399. }
  57400. });
  57401. }
  57402. }
  57403. }
  57404. };
  57405. FilesInput.prototype._processReload = function () {
  57406. if (this._onReloadCallback) {
  57407. this._onReloadCallback(this._sceneFileToLoad);
  57408. }
  57409. else {
  57410. this.reload();
  57411. }
  57412. };
  57413. FilesInput.prototype.reload = function () {
  57414. var _this = this;
  57415. // If a scene file has been provided
  57416. if (this._sceneFileToLoad) {
  57417. if (this._currentScene) {
  57418. if (BABYLON.Tools.errorsCount > 0) {
  57419. BABYLON.Tools.ClearLogCache();
  57420. }
  57421. this._engine.stopRenderLoop();
  57422. this._currentScene.dispose();
  57423. }
  57424. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  57425. _this._currentScene = newScene;
  57426. if (_this._sceneLoadedCallback) {
  57427. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  57428. }
  57429. // Wait for textures and shaders to be ready
  57430. _this._currentScene.executeWhenReady(function () {
  57431. _this._engine.runRenderLoop(function () {
  57432. _this.renderFunction();
  57433. });
  57434. });
  57435. }, function (progress) {
  57436. if (_this._progressCallback) {
  57437. _this._progressCallback(progress);
  57438. }
  57439. }, function (scene, message) {
  57440. _this._currentScene = scene;
  57441. if (_this._errorCallback) {
  57442. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  57443. }
  57444. });
  57445. }
  57446. else {
  57447. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  57448. }
  57449. };
  57450. FilesInput.FilesToLoad = {};
  57451. return FilesInput;
  57452. }());
  57453. BABYLON.FilesInput = FilesInput;
  57454. })(BABYLON || (BABYLON = {}));
  57455. //# sourceMappingURL=babylon.filesInput.js.map
  57456. var BABYLON;
  57457. (function (BABYLON) {
  57458. /**
  57459. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57460. * The underlying implementation relies on an associative array to ensure the best performances.
  57461. * The value can be anything including 'null' but except 'undefined'
  57462. */
  57463. var StringDictionary = /** @class */ (function () {
  57464. function StringDictionary() {
  57465. this._count = 0;
  57466. this._data = {};
  57467. }
  57468. /**
  57469. * This will clear this dictionary and copy the content from the 'source' one.
  57470. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57471. * @param source the dictionary to take the content from and copy to this dictionary
  57472. */
  57473. StringDictionary.prototype.copyFrom = function (source) {
  57474. var _this = this;
  57475. this.clear();
  57476. source.forEach(function (t, v) { return _this.add(t, v); });
  57477. };
  57478. /**
  57479. * Get a value based from its key
  57480. * @param key the given key to get the matching value from
  57481. * @return the value if found, otherwise undefined is returned
  57482. */
  57483. StringDictionary.prototype.get = function (key) {
  57484. var val = this._data[key];
  57485. if (val !== undefined) {
  57486. return val;
  57487. }
  57488. return undefined;
  57489. };
  57490. /**
  57491. * Get a value from its key or add it if it doesn't exist.
  57492. * This method will ensure you that a given key/data will be present in the dictionary.
  57493. * @param key the given key to get the matching value from
  57494. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57495. * The factory will only be invoked if there's no data for the given key.
  57496. * @return the value corresponding to the key.
  57497. */
  57498. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57499. var val = this.get(key);
  57500. if (val !== undefined) {
  57501. return val;
  57502. }
  57503. val = factory(key);
  57504. if (val) {
  57505. this.add(key, val);
  57506. }
  57507. return val;
  57508. };
  57509. /**
  57510. * Get a value from its key if present in the dictionary otherwise add it
  57511. * @param key the key to get the value from
  57512. * @param val if there's no such key/value pair in the dictionary add it with this value
  57513. * @return the value corresponding to the key
  57514. */
  57515. StringDictionary.prototype.getOrAdd = function (key, val) {
  57516. var curVal = this.get(key);
  57517. if (curVal !== undefined) {
  57518. return curVal;
  57519. }
  57520. this.add(key, val);
  57521. return val;
  57522. };
  57523. /**
  57524. * Check if there's a given key in the dictionary
  57525. * @param key the key to check for
  57526. * @return true if the key is present, false otherwise
  57527. */
  57528. StringDictionary.prototype.contains = function (key) {
  57529. return this._data[key] !== undefined;
  57530. };
  57531. /**
  57532. * Add a new key and its corresponding value
  57533. * @param key the key to add
  57534. * @param value the value corresponding to the key
  57535. * @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
  57536. */
  57537. StringDictionary.prototype.add = function (key, value) {
  57538. if (this._data[key] !== undefined) {
  57539. return false;
  57540. }
  57541. this._data[key] = value;
  57542. ++this._count;
  57543. return true;
  57544. };
  57545. StringDictionary.prototype.set = function (key, value) {
  57546. if (this._data[key] === undefined) {
  57547. return false;
  57548. }
  57549. this._data[key] = value;
  57550. return true;
  57551. };
  57552. /**
  57553. * Get the element of the given key and remove it from the dictionary
  57554. * @param key
  57555. */
  57556. StringDictionary.prototype.getAndRemove = function (key) {
  57557. var val = this.get(key);
  57558. if (val !== undefined) {
  57559. delete this._data[key];
  57560. --this._count;
  57561. return val;
  57562. }
  57563. return null;
  57564. };
  57565. /**
  57566. * Remove a key/value from the dictionary.
  57567. * @param key the key to remove
  57568. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  57569. */
  57570. StringDictionary.prototype.remove = function (key) {
  57571. if (this.contains(key)) {
  57572. delete this._data[key];
  57573. --this._count;
  57574. return true;
  57575. }
  57576. return false;
  57577. };
  57578. /**
  57579. * Clear the whole content of the dictionary
  57580. */
  57581. StringDictionary.prototype.clear = function () {
  57582. this._data = {};
  57583. this._count = 0;
  57584. };
  57585. Object.defineProperty(StringDictionary.prototype, "count", {
  57586. get: function () {
  57587. return this._count;
  57588. },
  57589. enumerable: true,
  57590. configurable: true
  57591. });
  57592. /**
  57593. * Execute a callback on each key/val of the dictionary.
  57594. * Note that you can remove any element in this dictionary in the callback implementation
  57595. * @param callback the callback to execute on a given key/value pair
  57596. */
  57597. StringDictionary.prototype.forEach = function (callback) {
  57598. for (var cur in this._data) {
  57599. var val = this._data[cur];
  57600. callback(cur, val);
  57601. }
  57602. };
  57603. /**
  57604. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  57605. * If the callback returns null or undefined the method will iterate to the next key/value pair
  57606. * Note that you can remove any element in this dictionary in the callback implementation
  57607. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  57608. */
  57609. StringDictionary.prototype.first = function (callback) {
  57610. for (var cur in this._data) {
  57611. var val = this._data[cur];
  57612. var res = callback(cur, val);
  57613. if (res) {
  57614. return res;
  57615. }
  57616. }
  57617. return null;
  57618. };
  57619. return StringDictionary;
  57620. }());
  57621. BABYLON.StringDictionary = StringDictionary;
  57622. })(BABYLON || (BABYLON = {}));
  57623. //# sourceMappingURL=babylon.stringDictionary.js.map
  57624. var BABYLON;
  57625. (function (BABYLON) {
  57626. var Tags = /** @class */ (function () {
  57627. function Tags() {
  57628. }
  57629. Tags.EnableFor = function (obj) {
  57630. obj._tags = obj._tags || {};
  57631. obj.hasTags = function () {
  57632. return Tags.HasTags(obj);
  57633. };
  57634. obj.addTags = function (tagsString) {
  57635. return Tags.AddTagsTo(obj, tagsString);
  57636. };
  57637. obj.removeTags = function (tagsString) {
  57638. return Tags.RemoveTagsFrom(obj, tagsString);
  57639. };
  57640. obj.matchesTagsQuery = function (tagsQuery) {
  57641. return Tags.MatchesQuery(obj, tagsQuery);
  57642. };
  57643. };
  57644. Tags.DisableFor = function (obj) {
  57645. delete obj._tags;
  57646. delete obj.hasTags;
  57647. delete obj.addTags;
  57648. delete obj.removeTags;
  57649. delete obj.matchesTagsQuery;
  57650. };
  57651. Tags.HasTags = function (obj) {
  57652. if (!obj._tags) {
  57653. return false;
  57654. }
  57655. return !BABYLON.Tools.IsEmpty(obj._tags);
  57656. };
  57657. Tags.GetTags = function (obj, asString) {
  57658. if (asString === void 0) { asString = true; }
  57659. if (!obj._tags) {
  57660. return null;
  57661. }
  57662. if (asString) {
  57663. var tagsArray = [];
  57664. for (var tag in obj._tags) {
  57665. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  57666. tagsArray.push(tag);
  57667. }
  57668. }
  57669. return tagsArray.join(" ");
  57670. }
  57671. else {
  57672. return obj._tags;
  57673. }
  57674. };
  57675. // the tags 'true' and 'false' are reserved and cannot be used as tags
  57676. // a tag cannot start with '||', '&&', and '!'
  57677. // it cannot contain whitespaces
  57678. Tags.AddTagsTo = function (obj, tagsString) {
  57679. if (!tagsString) {
  57680. return;
  57681. }
  57682. if (typeof tagsString !== "string") {
  57683. return;
  57684. }
  57685. var tags = tagsString.split(" ");
  57686. tags.forEach(function (tag, index, array) {
  57687. Tags._AddTagTo(obj, tag);
  57688. });
  57689. };
  57690. Tags._AddTagTo = function (obj, tag) {
  57691. tag = tag.trim();
  57692. if (tag === "" || tag === "true" || tag === "false") {
  57693. return;
  57694. }
  57695. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  57696. return;
  57697. }
  57698. Tags.EnableFor(obj);
  57699. obj._tags[tag] = true;
  57700. };
  57701. Tags.RemoveTagsFrom = function (obj, tagsString) {
  57702. if (!Tags.HasTags(obj)) {
  57703. return;
  57704. }
  57705. var tags = tagsString.split(" ");
  57706. for (var t in tags) {
  57707. Tags._RemoveTagFrom(obj, tags[t]);
  57708. }
  57709. };
  57710. Tags._RemoveTagFrom = function (obj, tag) {
  57711. delete obj._tags[tag];
  57712. };
  57713. Tags.MatchesQuery = function (obj, tagsQuery) {
  57714. if (tagsQuery === undefined) {
  57715. return true;
  57716. }
  57717. if (tagsQuery === "") {
  57718. return Tags.HasTags(obj);
  57719. }
  57720. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  57721. };
  57722. return Tags;
  57723. }());
  57724. BABYLON.Tags = Tags;
  57725. })(BABYLON || (BABYLON = {}));
  57726. //# sourceMappingURL=babylon.tags.js.map
  57727. var BABYLON;
  57728. (function (BABYLON) {
  57729. var AndOrNotEvaluator = /** @class */ (function () {
  57730. function AndOrNotEvaluator() {
  57731. }
  57732. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  57733. if (!query.match(/\([^\(\)]*\)/g)) {
  57734. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  57735. }
  57736. else {
  57737. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  57738. // remove parenthesis
  57739. r = r.slice(1, r.length - 1);
  57740. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  57741. });
  57742. }
  57743. if (query === "true") {
  57744. return true;
  57745. }
  57746. if (query === "false") {
  57747. return false;
  57748. }
  57749. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  57750. };
  57751. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  57752. evaluateCallback = evaluateCallback || (function (r) {
  57753. return r === "true" ? true : false;
  57754. });
  57755. var result;
  57756. var or = parenthesisContent.split("||");
  57757. for (var i in or) {
  57758. if (or.hasOwnProperty(i)) {
  57759. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  57760. var and = ori.split("&&");
  57761. if (and.length > 1) {
  57762. for (var j = 0; j < and.length; ++j) {
  57763. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  57764. if (andj !== "true" && andj !== "false") {
  57765. if (andj[0] === "!") {
  57766. result = !evaluateCallback(andj.substring(1));
  57767. }
  57768. else {
  57769. result = evaluateCallback(andj);
  57770. }
  57771. }
  57772. else {
  57773. result = andj === "true" ? true : false;
  57774. }
  57775. if (!result) {
  57776. ori = "false";
  57777. break;
  57778. }
  57779. }
  57780. }
  57781. if (result || ori === "true") {
  57782. result = true;
  57783. break;
  57784. }
  57785. // result equals false (or undefined)
  57786. if (ori !== "true" && ori !== "false") {
  57787. if (ori[0] === "!") {
  57788. result = !evaluateCallback(ori.substring(1));
  57789. }
  57790. else {
  57791. result = evaluateCallback(ori);
  57792. }
  57793. }
  57794. else {
  57795. result = ori === "true" ? true : false;
  57796. }
  57797. }
  57798. }
  57799. // the whole parenthesis scope is replaced by 'true' or 'false'
  57800. return result ? "true" : "false";
  57801. };
  57802. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  57803. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  57804. // remove whitespaces
  57805. r = r.replace(/[\s]/g, function () { return ""; });
  57806. return r.length % 2 ? "!" : "";
  57807. });
  57808. booleanString = booleanString.trim();
  57809. if (booleanString === "!true") {
  57810. booleanString = "false";
  57811. }
  57812. else if (booleanString === "!false") {
  57813. booleanString = "true";
  57814. }
  57815. return booleanString;
  57816. };
  57817. return AndOrNotEvaluator;
  57818. }());
  57819. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  57820. })(BABYLON || (BABYLON = {}));
  57821. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  57822. var BABYLON;
  57823. (function (BABYLON) {
  57824. var Database = /** @class */ (function () {
  57825. function Database(urlToScene, callbackManifestChecked) {
  57826. // Handling various flavors of prefixed version of IndexedDB
  57827. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  57828. this.callbackManifestChecked = callbackManifestChecked;
  57829. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  57830. this.db = null;
  57831. this._enableSceneOffline = false;
  57832. this._enableTexturesOffline = false;
  57833. this.manifestVersionFound = 0;
  57834. this.mustUpdateRessources = false;
  57835. this.hasReachedQuota = false;
  57836. if (!Database.IDBStorageEnabled) {
  57837. this.callbackManifestChecked(true);
  57838. }
  57839. else {
  57840. this.checkManifestFile();
  57841. }
  57842. }
  57843. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  57844. get: function () {
  57845. return this._enableSceneOffline;
  57846. },
  57847. enumerable: true,
  57848. configurable: true
  57849. });
  57850. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  57851. get: function () {
  57852. return this._enableTexturesOffline;
  57853. },
  57854. enumerable: true,
  57855. configurable: true
  57856. });
  57857. Database.prototype.checkManifestFile = function () {
  57858. var _this = this;
  57859. var noManifestFile = function () {
  57860. _this._enableSceneOffline = false;
  57861. _this._enableTexturesOffline = false;
  57862. _this.callbackManifestChecked(false);
  57863. };
  57864. var timeStampUsed = false;
  57865. var manifestURL = this.currentSceneUrl + ".manifest";
  57866. var xhr = new XMLHttpRequest();
  57867. if (navigator.onLine) {
  57868. // Adding a timestamp to by-pass browsers' cache
  57869. timeStampUsed = true;
  57870. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  57871. }
  57872. xhr.open("GET", manifestURL, true);
  57873. xhr.addEventListener("load", function () {
  57874. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57875. try {
  57876. var manifestFile = JSON.parse(xhr.response);
  57877. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  57878. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  57879. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  57880. _this.manifestVersionFound = manifestFile.version;
  57881. }
  57882. if (_this.callbackManifestChecked) {
  57883. _this.callbackManifestChecked(true);
  57884. }
  57885. }
  57886. catch (ex) {
  57887. noManifestFile();
  57888. }
  57889. }
  57890. else {
  57891. noManifestFile();
  57892. }
  57893. }, false);
  57894. xhr.addEventListener("error", function (event) {
  57895. if (timeStampUsed) {
  57896. timeStampUsed = false;
  57897. // Let's retry without the timeStamp
  57898. // It could fail when coupled with HTML5 Offline API
  57899. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  57900. xhr.open("GET", retryManifestURL, true);
  57901. xhr.send();
  57902. }
  57903. else {
  57904. noManifestFile();
  57905. }
  57906. }, false);
  57907. try {
  57908. xhr.send();
  57909. }
  57910. catch (ex) {
  57911. BABYLON.Tools.Error("Error on XHR send request.");
  57912. this.callbackManifestChecked(false);
  57913. }
  57914. };
  57915. Database.prototype.openAsync = function (successCallback, errorCallback) {
  57916. var _this = this;
  57917. var handleError = function () {
  57918. _this.isSupported = false;
  57919. if (errorCallback)
  57920. errorCallback();
  57921. };
  57922. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  57923. // Your browser doesn't support IndexedDB
  57924. this.isSupported = false;
  57925. if (errorCallback)
  57926. errorCallback();
  57927. }
  57928. else {
  57929. // If the DB hasn't been opened or created yet
  57930. if (!this.db) {
  57931. this.hasReachedQuota = false;
  57932. this.isSupported = true;
  57933. var request = this.idbFactory.open("babylonjs", 1);
  57934. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  57935. request.onerror = function (event) {
  57936. handleError();
  57937. };
  57938. // executes when a version change transaction cannot complete due to other active transactions
  57939. request.onblocked = function (event) {
  57940. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  57941. handleError();
  57942. };
  57943. // DB has been opened successfully
  57944. request.onsuccess = function (event) {
  57945. _this.db = request.result;
  57946. successCallback();
  57947. };
  57948. // Initialization of the DB. Creating Scenes & Textures stores
  57949. request.onupgradeneeded = function (event) {
  57950. _this.db = (event.target).result;
  57951. if (_this.db) {
  57952. try {
  57953. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  57954. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  57955. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  57956. }
  57957. catch (ex) {
  57958. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  57959. handleError();
  57960. }
  57961. }
  57962. };
  57963. }
  57964. else {
  57965. if (successCallback)
  57966. successCallback();
  57967. }
  57968. }
  57969. };
  57970. Database.prototype.loadImageFromDB = function (url, image) {
  57971. var _this = this;
  57972. var completeURL = Database.ReturnFullUrlLocation(url);
  57973. var saveAndLoadImage = function () {
  57974. if (!_this.hasReachedQuota && _this.db !== null) {
  57975. // the texture is not yet in the DB, let's try to save it
  57976. _this._saveImageIntoDBAsync(completeURL, image);
  57977. }
  57978. else {
  57979. image.src = url;
  57980. }
  57981. };
  57982. if (!this.mustUpdateRessources) {
  57983. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  57984. }
  57985. else {
  57986. saveAndLoadImage();
  57987. }
  57988. };
  57989. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  57990. if (this.isSupported && this.db !== null) {
  57991. var texture;
  57992. var transaction = this.db.transaction(["textures"]);
  57993. transaction.onabort = function (event) {
  57994. image.src = url;
  57995. };
  57996. transaction.oncomplete = function (event) {
  57997. var blobTextureURL;
  57998. if (texture) {
  57999. var URL = window.URL || window.webkitURL;
  58000. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  58001. image.onerror = function () {
  58002. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  58003. image.src = url;
  58004. };
  58005. image.src = blobTextureURL;
  58006. }
  58007. else {
  58008. notInDBCallback();
  58009. }
  58010. };
  58011. var getRequest = transaction.objectStore("textures").get(url);
  58012. getRequest.onsuccess = function (event) {
  58013. texture = (event.target).result;
  58014. };
  58015. getRequest.onerror = function (event) {
  58016. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  58017. image.src = url;
  58018. };
  58019. }
  58020. else {
  58021. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58022. image.src = url;
  58023. }
  58024. };
  58025. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  58026. var _this = this;
  58027. if (this.isSupported) {
  58028. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  58029. var generateBlobUrl = function () {
  58030. var blobTextureURL;
  58031. if (blob) {
  58032. var URL = window.URL || window.webkitURL;
  58033. try {
  58034. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  58035. }
  58036. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  58037. catch (ex) {
  58038. blobTextureURL = URL.createObjectURL(blob);
  58039. }
  58040. }
  58041. if (blobTextureURL) {
  58042. image.src = blobTextureURL;
  58043. }
  58044. };
  58045. if (Database.IsUASupportingBlobStorage) {
  58046. var xhr = new XMLHttpRequest(), blob;
  58047. xhr.open("GET", url, true);
  58048. xhr.responseType = "blob";
  58049. xhr.addEventListener("load", function () {
  58050. if (xhr.status === 200 && _this.db) {
  58051. // Blob as response (XHR2)
  58052. blob = xhr.response;
  58053. var transaction = _this.db.transaction(["textures"], "readwrite");
  58054. // the transaction could abort because of a QuotaExceededError error
  58055. transaction.onabort = function (event) {
  58056. try {
  58057. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58058. var srcElement = (event.srcElement || event.target);
  58059. var error = srcElement.error;
  58060. if (error && error.name === "QuotaExceededError") {
  58061. _this.hasReachedQuota = true;
  58062. }
  58063. }
  58064. catch (ex) { }
  58065. generateBlobUrl();
  58066. };
  58067. transaction.oncomplete = function (event) {
  58068. generateBlobUrl();
  58069. };
  58070. var newTexture = { textureUrl: url, data: blob };
  58071. try {
  58072. // Put the blob into the dabase
  58073. var addRequest = transaction.objectStore("textures").put(newTexture);
  58074. addRequest.onsuccess = function (event) {
  58075. };
  58076. addRequest.onerror = function (event) {
  58077. generateBlobUrl();
  58078. };
  58079. }
  58080. catch (ex) {
  58081. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  58082. if (ex.code === 25) {
  58083. Database.IsUASupportingBlobStorage = false;
  58084. }
  58085. image.src = url;
  58086. }
  58087. }
  58088. else {
  58089. image.src = url;
  58090. }
  58091. }, false);
  58092. xhr.addEventListener("error", function (event) {
  58093. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  58094. image.src = url;
  58095. }, false);
  58096. xhr.send();
  58097. }
  58098. else {
  58099. image.src = url;
  58100. }
  58101. }
  58102. else {
  58103. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58104. image.src = url;
  58105. }
  58106. };
  58107. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  58108. var _this = this;
  58109. var updateVersion = function () {
  58110. // the version is not yet in the DB or we need to update it
  58111. _this._saveVersionIntoDBAsync(url, versionLoaded);
  58112. };
  58113. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  58114. };
  58115. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  58116. var _this = this;
  58117. if (this.isSupported && this.db) {
  58118. var version;
  58119. try {
  58120. var transaction = this.db.transaction(["versions"]);
  58121. transaction.oncomplete = function (event) {
  58122. if (version) {
  58123. // If the version in the JSON file is > than the version in DB
  58124. if (_this.manifestVersionFound > version.data) {
  58125. _this.mustUpdateRessources = true;
  58126. updateInDBCallback();
  58127. }
  58128. else {
  58129. callback(version.data);
  58130. }
  58131. }
  58132. else {
  58133. _this.mustUpdateRessources = true;
  58134. updateInDBCallback();
  58135. }
  58136. };
  58137. transaction.onabort = function (event) {
  58138. callback(-1);
  58139. };
  58140. var getRequest = transaction.objectStore("versions").get(url);
  58141. getRequest.onsuccess = function (event) {
  58142. version = (event.target).result;
  58143. };
  58144. getRequest.onerror = function (event) {
  58145. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  58146. callback(-1);
  58147. };
  58148. }
  58149. catch (ex) {
  58150. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  58151. callback(-1);
  58152. }
  58153. }
  58154. else {
  58155. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58156. callback(-1);
  58157. }
  58158. };
  58159. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  58160. var _this = this;
  58161. if (this.isSupported && !this.hasReachedQuota && this.db) {
  58162. try {
  58163. // Open a transaction to the database
  58164. var transaction = this.db.transaction(["versions"], "readwrite");
  58165. // the transaction could abort because of a QuotaExceededError error
  58166. transaction.onabort = function (event) {
  58167. try {
  58168. var error = event.srcElement['error'];
  58169. if (error && error.name === "QuotaExceededError") {
  58170. _this.hasReachedQuota = true;
  58171. }
  58172. }
  58173. catch (ex) { }
  58174. callback(-1);
  58175. };
  58176. transaction.oncomplete = function (event) {
  58177. callback(_this.manifestVersionFound);
  58178. };
  58179. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58180. // Put the scene into the database
  58181. var addRequest = transaction.objectStore("versions").put(newVersion);
  58182. addRequest.onsuccess = function (event) {
  58183. };
  58184. addRequest.onerror = function (event) {
  58185. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58186. };
  58187. }
  58188. catch (ex) {
  58189. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58190. callback(-1);
  58191. }
  58192. }
  58193. else {
  58194. callback(-1);
  58195. }
  58196. };
  58197. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58198. var _this = this;
  58199. var completeUrl = Database.ReturnFullUrlLocation(url);
  58200. var saveAndLoadFile = function () {
  58201. // the scene is not yet in the DB, let's try to save it
  58202. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58203. };
  58204. this._checkVersionFromDB(completeUrl, function (version) {
  58205. if (version !== -1) {
  58206. if (!_this.mustUpdateRessources) {
  58207. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58208. }
  58209. else {
  58210. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58211. }
  58212. }
  58213. else {
  58214. if (errorCallback) {
  58215. errorCallback();
  58216. }
  58217. }
  58218. });
  58219. };
  58220. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58221. if (this.isSupported && this.db) {
  58222. var targetStore;
  58223. if (url.indexOf(".babylon") !== -1) {
  58224. targetStore = "scenes";
  58225. }
  58226. else {
  58227. targetStore = "textures";
  58228. }
  58229. var file;
  58230. var transaction = this.db.transaction([targetStore]);
  58231. transaction.oncomplete = function (event) {
  58232. if (file) {
  58233. callback(file.data);
  58234. }
  58235. else {
  58236. notInDBCallback();
  58237. }
  58238. };
  58239. transaction.onabort = function (event) {
  58240. notInDBCallback();
  58241. };
  58242. var getRequest = transaction.objectStore(targetStore).get(url);
  58243. getRequest.onsuccess = function (event) {
  58244. file = (event.target).result;
  58245. };
  58246. getRequest.onerror = function (event) {
  58247. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58248. notInDBCallback();
  58249. };
  58250. }
  58251. else {
  58252. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58253. callback();
  58254. }
  58255. };
  58256. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58257. var _this = this;
  58258. if (this.isSupported) {
  58259. var targetStore;
  58260. if (url.indexOf(".babylon") !== -1) {
  58261. targetStore = "scenes";
  58262. }
  58263. else {
  58264. targetStore = "textures";
  58265. }
  58266. // Create XHR
  58267. var xhr = new XMLHttpRequest();
  58268. var fileData;
  58269. xhr.open("GET", url, true);
  58270. if (useArrayBuffer) {
  58271. xhr.responseType = "arraybuffer";
  58272. }
  58273. if (progressCallback) {
  58274. xhr.onprogress = progressCallback;
  58275. }
  58276. xhr.addEventListener("load", function () {
  58277. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58278. // Blob as response (XHR2)
  58279. //fileData = xhr.responseText;
  58280. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58281. if (!_this.hasReachedQuota && _this.db) {
  58282. // Open a transaction to the database
  58283. var transaction = _this.db.transaction([targetStore], "readwrite");
  58284. // the transaction could abort because of a QuotaExceededError error
  58285. transaction.onabort = function (event) {
  58286. try {
  58287. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58288. var error = event.srcElement['error'];
  58289. if (error && error.name === "QuotaExceededError") {
  58290. _this.hasReachedQuota = true;
  58291. }
  58292. }
  58293. catch (ex) { }
  58294. callback(fileData);
  58295. };
  58296. transaction.oncomplete = function (event) {
  58297. callback(fileData);
  58298. };
  58299. var newFile;
  58300. if (targetStore === "scenes") {
  58301. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58302. }
  58303. else {
  58304. newFile = { textureUrl: url, data: fileData };
  58305. }
  58306. try {
  58307. // Put the scene into the database
  58308. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58309. addRequest.onsuccess = function (event) {
  58310. };
  58311. addRequest.onerror = function (event) {
  58312. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58313. };
  58314. }
  58315. catch (ex) {
  58316. callback(fileData);
  58317. }
  58318. }
  58319. else {
  58320. callback(fileData);
  58321. }
  58322. }
  58323. else {
  58324. callback();
  58325. }
  58326. }, false);
  58327. xhr.addEventListener("error", function (event) {
  58328. BABYLON.Tools.Error("error on XHR request.");
  58329. callback();
  58330. }, false);
  58331. xhr.send();
  58332. }
  58333. else {
  58334. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58335. callback();
  58336. }
  58337. };
  58338. Database.IsUASupportingBlobStorage = true;
  58339. Database.IDBStorageEnabled = true;
  58340. Database.parseURL = function (url) {
  58341. var a = document.createElement('a');
  58342. a.href = url;
  58343. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58344. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58345. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58346. return absLocation;
  58347. };
  58348. Database.ReturnFullUrlLocation = function (url) {
  58349. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58350. return (Database.parseURL(window.location.href) + url);
  58351. }
  58352. else {
  58353. return url;
  58354. }
  58355. };
  58356. return Database;
  58357. }());
  58358. BABYLON.Database = Database;
  58359. })(BABYLON || (BABYLON = {}));
  58360. //# sourceMappingURL=babylon.database.js.map
  58361. var BABYLON;
  58362. (function (BABYLON) {
  58363. var FresnelParameters = /** @class */ (function () {
  58364. function FresnelParameters() {
  58365. this._isEnabled = true;
  58366. this.leftColor = BABYLON.Color3.White();
  58367. this.rightColor = BABYLON.Color3.Black();
  58368. this.bias = 0;
  58369. this.power = 1;
  58370. }
  58371. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58372. get: function () {
  58373. return this._isEnabled;
  58374. },
  58375. set: function (value) {
  58376. if (this._isEnabled === value) {
  58377. return;
  58378. }
  58379. this._isEnabled = value;
  58380. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  58381. },
  58382. enumerable: true,
  58383. configurable: true
  58384. });
  58385. FresnelParameters.prototype.clone = function () {
  58386. var newFresnelParameters = new FresnelParameters();
  58387. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58388. return newFresnelParameters;
  58389. };
  58390. FresnelParameters.prototype.serialize = function () {
  58391. var serializationObject = {};
  58392. serializationObject.isEnabled = this.isEnabled;
  58393. serializationObject.leftColor = this.leftColor;
  58394. serializationObject.rightColor = this.rightColor;
  58395. serializationObject.bias = this.bias;
  58396. serializationObject.power = this.power;
  58397. return serializationObject;
  58398. };
  58399. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58400. var fresnelParameters = new FresnelParameters();
  58401. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58402. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58403. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58404. fresnelParameters.bias = parsedFresnelParameters.bias;
  58405. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58406. return fresnelParameters;
  58407. };
  58408. return FresnelParameters;
  58409. }());
  58410. BABYLON.FresnelParameters = FresnelParameters;
  58411. })(BABYLON || (BABYLON = {}));
  58412. //# sourceMappingURL=babylon.fresnelParameters.js.map
  58413. var BABYLON;
  58414. (function (BABYLON) {
  58415. var MultiMaterial = /** @class */ (function (_super) {
  58416. __extends(MultiMaterial, _super);
  58417. function MultiMaterial(name, scene) {
  58418. var _this = _super.call(this, name, scene, true) || this;
  58419. scene.multiMaterials.push(_this);
  58420. _this.subMaterials = new Array();
  58421. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  58422. return _this;
  58423. }
  58424. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  58425. get: function () {
  58426. return this._subMaterials;
  58427. },
  58428. set: function (value) {
  58429. this._subMaterials = value;
  58430. this._hookArray(value);
  58431. },
  58432. enumerable: true,
  58433. configurable: true
  58434. });
  58435. MultiMaterial.prototype._hookArray = function (array) {
  58436. var _this = this;
  58437. var oldPush = array.push;
  58438. array.push = function () {
  58439. var items = [];
  58440. for (var _i = 0; _i < arguments.length; _i++) {
  58441. items[_i] = arguments[_i];
  58442. }
  58443. var result = oldPush.apply(array, items);
  58444. _this._markAllSubMeshesAsTexturesDirty();
  58445. return result;
  58446. };
  58447. var oldSplice = array.splice;
  58448. array.splice = function (index, deleteCount) {
  58449. var deleted = oldSplice.apply(array, [index, deleteCount]);
  58450. _this._markAllSubMeshesAsTexturesDirty();
  58451. return deleted;
  58452. };
  58453. };
  58454. // Properties
  58455. MultiMaterial.prototype.getSubMaterial = function (index) {
  58456. if (index < 0 || index >= this.subMaterials.length) {
  58457. return this.getScene().defaultMaterial;
  58458. }
  58459. return this.subMaterials[index];
  58460. };
  58461. MultiMaterial.prototype.getActiveTextures = function () {
  58462. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  58463. if (subMaterial) {
  58464. return subMaterial.getActiveTextures();
  58465. }
  58466. else {
  58467. return [];
  58468. }
  58469. }));
  58470. var _a;
  58471. };
  58472. // Methods
  58473. MultiMaterial.prototype.getClassName = function () {
  58474. return "MultiMaterial";
  58475. };
  58476. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  58477. for (var index = 0; index < this.subMaterials.length; index++) {
  58478. var subMaterial = this.subMaterials[index];
  58479. if (subMaterial) {
  58480. if (subMaterial.storeEffectOnSubMeshes) {
  58481. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  58482. return false;
  58483. }
  58484. continue;
  58485. }
  58486. if (!subMaterial.isReady(mesh)) {
  58487. return false;
  58488. }
  58489. }
  58490. }
  58491. return true;
  58492. };
  58493. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  58494. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  58495. for (var index = 0; index < this.subMaterials.length; index++) {
  58496. var subMaterial = null;
  58497. var current = this.subMaterials[index];
  58498. if (cloneChildren && current) {
  58499. subMaterial = current.clone(name + "-" + current.name);
  58500. }
  58501. else {
  58502. subMaterial = this.subMaterials[index];
  58503. }
  58504. newMultiMaterial.subMaterials.push(subMaterial);
  58505. }
  58506. return newMultiMaterial;
  58507. };
  58508. MultiMaterial.prototype.serialize = function () {
  58509. var serializationObject = {};
  58510. serializationObject.name = this.name;
  58511. serializationObject.id = this.id;
  58512. if (BABYLON.Tags) {
  58513. serializationObject.tags = BABYLON.Tags.GetTags(this);
  58514. }
  58515. serializationObject.materials = [];
  58516. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  58517. var subMat = this.subMaterials[matIndex];
  58518. if (subMat) {
  58519. serializationObject.materials.push(subMat.id);
  58520. }
  58521. else {
  58522. serializationObject.materials.push(null);
  58523. }
  58524. }
  58525. return serializationObject;
  58526. };
  58527. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58528. var scene = this.getScene();
  58529. if (!scene) {
  58530. return;
  58531. }
  58532. var index = scene.multiMaterials.indexOf(this);
  58533. if (index >= 0) {
  58534. scene.multiMaterials.splice(index, 1);
  58535. }
  58536. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58537. };
  58538. return MultiMaterial;
  58539. }(BABYLON.Material));
  58540. BABYLON.MultiMaterial = MultiMaterial;
  58541. })(BABYLON || (BABYLON = {}));
  58542. //# sourceMappingURL=babylon.multiMaterial.js.map
  58543. var BABYLON;
  58544. (function (BABYLON) {
  58545. var FreeCameraTouchInput = /** @class */ (function () {
  58546. function FreeCameraTouchInput() {
  58547. this._offsetX = null;
  58548. this._offsetY = null;
  58549. this._pointerPressed = new Array();
  58550. this.touchAngularSensibility = 200000.0;
  58551. this.touchMoveSensibility = 250.0;
  58552. }
  58553. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  58554. var _this = this;
  58555. var previousPosition = null;
  58556. if (this._pointerInput === undefined) {
  58557. this._onLostFocus = function (evt) {
  58558. _this._offsetX = null;
  58559. _this._offsetY = null;
  58560. };
  58561. this._pointerInput = function (p, s) {
  58562. var evt = p.event;
  58563. if (evt.pointerType === "mouse") {
  58564. return;
  58565. }
  58566. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  58567. if (!noPreventDefault) {
  58568. evt.preventDefault();
  58569. }
  58570. _this._pointerPressed.push(evt.pointerId);
  58571. if (_this._pointerPressed.length !== 1) {
  58572. return;
  58573. }
  58574. previousPosition = {
  58575. x: evt.clientX,
  58576. y: evt.clientY
  58577. };
  58578. }
  58579. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  58580. if (!noPreventDefault) {
  58581. evt.preventDefault();
  58582. }
  58583. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58584. if (index === -1) {
  58585. return;
  58586. }
  58587. _this._pointerPressed.splice(index, 1);
  58588. if (index != 0) {
  58589. return;
  58590. }
  58591. previousPosition = null;
  58592. _this._offsetX = null;
  58593. _this._offsetY = null;
  58594. }
  58595. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  58596. if (!noPreventDefault) {
  58597. evt.preventDefault();
  58598. }
  58599. if (!previousPosition) {
  58600. return;
  58601. }
  58602. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58603. if (index != 0) {
  58604. return;
  58605. }
  58606. _this._offsetX = evt.clientX - previousPosition.x;
  58607. _this._offsetY = -(evt.clientY - previousPosition.y);
  58608. }
  58609. };
  58610. }
  58611. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  58612. if (this._onLostFocus) {
  58613. element.addEventListener("blur", this._onLostFocus);
  58614. }
  58615. };
  58616. FreeCameraTouchInput.prototype.detachControl = function (element) {
  58617. if (this._pointerInput && element) {
  58618. if (this._observer) {
  58619. this.camera.getScene().onPointerObservable.remove(this._observer);
  58620. this._observer = null;
  58621. }
  58622. if (this._onLostFocus) {
  58623. element.removeEventListener("blur", this._onLostFocus);
  58624. this._onLostFocus = null;
  58625. }
  58626. this._pointerPressed = [];
  58627. this._offsetX = null;
  58628. this._offsetY = null;
  58629. }
  58630. };
  58631. FreeCameraTouchInput.prototype.checkInputs = function () {
  58632. if (this._offsetX && this._offsetY) {
  58633. var camera = this.camera;
  58634. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  58635. if (this._pointerPressed.length > 1) {
  58636. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  58637. }
  58638. else {
  58639. var speed = camera._computeLocalCameraSpeed();
  58640. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  58641. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  58642. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  58643. }
  58644. }
  58645. };
  58646. FreeCameraTouchInput.prototype.getClassName = function () {
  58647. return "FreeCameraTouchInput";
  58648. };
  58649. FreeCameraTouchInput.prototype.getSimpleName = function () {
  58650. return "touch";
  58651. };
  58652. __decorate([
  58653. BABYLON.serialize()
  58654. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  58655. __decorate([
  58656. BABYLON.serialize()
  58657. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  58658. return FreeCameraTouchInput;
  58659. }());
  58660. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  58661. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  58662. })(BABYLON || (BABYLON = {}));
  58663. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  58664. var BABYLON;
  58665. (function (BABYLON) {
  58666. // We're mainly based on the logic defined into the FreeCamera code
  58667. var TouchCamera = /** @class */ (function (_super) {
  58668. __extends(TouchCamera, _super);
  58669. //-- end properties for backward compatibility for inputs
  58670. function TouchCamera(name, position, scene) {
  58671. var _this = _super.call(this, name, position, scene) || this;
  58672. _this.inputs.addTouch();
  58673. _this._setupInputs();
  58674. return _this;
  58675. }
  58676. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  58677. //-- Begin properties for backward compatibility for inputs
  58678. get: function () {
  58679. var touch = this.inputs.attached["touch"];
  58680. if (touch)
  58681. return touch.touchAngularSensibility;
  58682. return 0;
  58683. },
  58684. set: function (value) {
  58685. var touch = this.inputs.attached["touch"];
  58686. if (touch)
  58687. touch.touchAngularSensibility = value;
  58688. },
  58689. enumerable: true,
  58690. configurable: true
  58691. });
  58692. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  58693. get: function () {
  58694. var touch = this.inputs.attached["touch"];
  58695. if (touch)
  58696. return touch.touchMoveSensibility;
  58697. return 0;
  58698. },
  58699. set: function (value) {
  58700. var touch = this.inputs.attached["touch"];
  58701. if (touch)
  58702. touch.touchMoveSensibility = value;
  58703. },
  58704. enumerable: true,
  58705. configurable: true
  58706. });
  58707. TouchCamera.prototype.getClassName = function () {
  58708. return "TouchCamera";
  58709. };
  58710. TouchCamera.prototype._setupInputs = function () {
  58711. var mouse = this.inputs.attached["mouse"];
  58712. if (mouse) {
  58713. mouse.touchEnabled = false;
  58714. }
  58715. };
  58716. return TouchCamera;
  58717. }(BABYLON.FreeCamera));
  58718. BABYLON.TouchCamera = TouchCamera;
  58719. })(BABYLON || (BABYLON = {}));
  58720. //# sourceMappingURL=babylon.touchCamera.js.map
  58721. var BABYLON;
  58722. (function (BABYLON) {
  58723. var ProceduralTexture = /** @class */ (function (_super) {
  58724. __extends(ProceduralTexture, _super);
  58725. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  58726. if (fallbackTexture === void 0) { fallbackTexture = null; }
  58727. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58728. if (isCube === void 0) { isCube = false; }
  58729. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58730. _this.isCube = isCube;
  58731. _this.isEnabled = true;
  58732. _this._currentRefreshId = -1;
  58733. _this._refreshRate = 1;
  58734. _this._vertexBuffers = {};
  58735. _this._uniforms = new Array();
  58736. _this._samplers = new Array();
  58737. _this._textures = {};
  58738. _this._floats = {};
  58739. _this._floatsArrays = {};
  58740. _this._colors3 = {};
  58741. _this._colors4 = {};
  58742. _this._vectors2 = {};
  58743. _this._vectors3 = {};
  58744. _this._matrices = {};
  58745. _this._fallbackTextureUsed = false;
  58746. scene._proceduralTextures.push(_this);
  58747. _this._engine = scene.getEngine();
  58748. _this.name = name;
  58749. _this.isRenderTarget = true;
  58750. _this._size = size;
  58751. _this._generateMipMaps = generateMipMaps;
  58752. _this.setFragment(fragment);
  58753. _this._fallbackTexture = fallbackTexture;
  58754. if (isCube) {
  58755. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  58756. _this.setFloat("face", 0);
  58757. }
  58758. else {
  58759. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  58760. }
  58761. // VBO
  58762. var vertices = [];
  58763. vertices.push(1, 1);
  58764. vertices.push(-1, 1);
  58765. vertices.push(-1, -1);
  58766. vertices.push(1, -1);
  58767. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58768. _this._createIndexBuffer();
  58769. return _this;
  58770. }
  58771. ProceduralTexture.prototype._createIndexBuffer = function () {
  58772. var engine = this._engine;
  58773. // Indices
  58774. var indices = [];
  58775. indices.push(0);
  58776. indices.push(1);
  58777. indices.push(2);
  58778. indices.push(0);
  58779. indices.push(2);
  58780. indices.push(3);
  58781. this._indexBuffer = engine.createIndexBuffer(indices);
  58782. };
  58783. ProceduralTexture.prototype._rebuild = function () {
  58784. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58785. if (vb) {
  58786. vb._rebuild();
  58787. }
  58788. this._createIndexBuffer();
  58789. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58790. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58791. }
  58792. };
  58793. ProceduralTexture.prototype.reset = function () {
  58794. if (this._effect === undefined) {
  58795. return;
  58796. }
  58797. var engine = this._engine;
  58798. engine._releaseEffect(this._effect);
  58799. };
  58800. ProceduralTexture.prototype.isReady = function () {
  58801. var _this = this;
  58802. var engine = this._engine;
  58803. var shaders;
  58804. if (!this._fragment) {
  58805. return false;
  58806. }
  58807. if (this._fallbackTextureUsed) {
  58808. return true;
  58809. }
  58810. if (this._fragment.fragmentElement !== undefined) {
  58811. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  58812. }
  58813. else {
  58814. shaders = { vertex: "procedural", fragment: this._fragment };
  58815. }
  58816. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  58817. _this.releaseInternalTexture();
  58818. if (_this._fallbackTexture) {
  58819. _this._texture = _this._fallbackTexture._texture;
  58820. if (_this._texture) {
  58821. _this._texture.incrementReferences();
  58822. }
  58823. }
  58824. _this._fallbackTextureUsed = true;
  58825. });
  58826. return this._effect.isReady();
  58827. };
  58828. ProceduralTexture.prototype.resetRefreshCounter = function () {
  58829. this._currentRefreshId = -1;
  58830. };
  58831. ProceduralTexture.prototype.setFragment = function (fragment) {
  58832. this._fragment = fragment;
  58833. };
  58834. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  58835. get: function () {
  58836. return this._refreshRate;
  58837. },
  58838. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58839. set: function (value) {
  58840. this._refreshRate = value;
  58841. this.resetRefreshCounter();
  58842. },
  58843. enumerable: true,
  58844. configurable: true
  58845. });
  58846. ProceduralTexture.prototype._shouldRender = function () {
  58847. if (!this.isEnabled || !this.isReady() || !this._texture) {
  58848. return false;
  58849. }
  58850. if (this._fallbackTextureUsed) {
  58851. return false;
  58852. }
  58853. if (this._currentRefreshId === -1) {
  58854. this._currentRefreshId = 1;
  58855. return true;
  58856. }
  58857. if (this.refreshRate === this._currentRefreshId) {
  58858. this._currentRefreshId = 1;
  58859. return true;
  58860. }
  58861. this._currentRefreshId++;
  58862. return false;
  58863. };
  58864. ProceduralTexture.prototype.getRenderSize = function () {
  58865. return this._size;
  58866. };
  58867. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  58868. if (this._fallbackTextureUsed) {
  58869. return;
  58870. }
  58871. this.releaseInternalTexture();
  58872. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  58873. };
  58874. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  58875. if (this._uniforms.indexOf(uniformName) === -1) {
  58876. this._uniforms.push(uniformName);
  58877. }
  58878. };
  58879. ProceduralTexture.prototype.setTexture = function (name, texture) {
  58880. if (this._samplers.indexOf(name) === -1) {
  58881. this._samplers.push(name);
  58882. }
  58883. this._textures[name] = texture;
  58884. return this;
  58885. };
  58886. ProceduralTexture.prototype.setFloat = function (name, value) {
  58887. this._checkUniform(name);
  58888. this._floats[name] = value;
  58889. return this;
  58890. };
  58891. ProceduralTexture.prototype.setFloats = function (name, value) {
  58892. this._checkUniform(name);
  58893. this._floatsArrays[name] = value;
  58894. return this;
  58895. };
  58896. ProceduralTexture.prototype.setColor3 = function (name, value) {
  58897. this._checkUniform(name);
  58898. this._colors3[name] = value;
  58899. return this;
  58900. };
  58901. ProceduralTexture.prototype.setColor4 = function (name, value) {
  58902. this._checkUniform(name);
  58903. this._colors4[name] = value;
  58904. return this;
  58905. };
  58906. ProceduralTexture.prototype.setVector2 = function (name, value) {
  58907. this._checkUniform(name);
  58908. this._vectors2[name] = value;
  58909. return this;
  58910. };
  58911. ProceduralTexture.prototype.setVector3 = function (name, value) {
  58912. this._checkUniform(name);
  58913. this._vectors3[name] = value;
  58914. return this;
  58915. };
  58916. ProceduralTexture.prototype.setMatrix = function (name, value) {
  58917. this._checkUniform(name);
  58918. this._matrices[name] = value;
  58919. return this;
  58920. };
  58921. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  58922. var scene = this.getScene();
  58923. if (!scene) {
  58924. return;
  58925. }
  58926. var engine = this._engine;
  58927. // Render
  58928. engine.enableEffect(this._effect);
  58929. engine.setState(false);
  58930. // Texture
  58931. for (var name in this._textures) {
  58932. this._effect.setTexture(name, this._textures[name]);
  58933. }
  58934. // Float
  58935. for (name in this._floats) {
  58936. this._effect.setFloat(name, this._floats[name]);
  58937. }
  58938. // Floats
  58939. for (name in this._floatsArrays) {
  58940. this._effect.setArray(name, this._floatsArrays[name]);
  58941. }
  58942. // Color3
  58943. for (name in this._colors3) {
  58944. this._effect.setColor3(name, this._colors3[name]);
  58945. }
  58946. // Color4
  58947. for (name in this._colors4) {
  58948. var color = this._colors4[name];
  58949. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58950. }
  58951. // Vector2
  58952. for (name in this._vectors2) {
  58953. this._effect.setVector2(name, this._vectors2[name]);
  58954. }
  58955. // Vector3
  58956. for (name in this._vectors3) {
  58957. this._effect.setVector3(name, this._vectors3[name]);
  58958. }
  58959. // Matrix
  58960. for (name in this._matrices) {
  58961. this._effect.setMatrix(name, this._matrices[name]);
  58962. }
  58963. if (!this._texture) {
  58964. return;
  58965. }
  58966. if (this.isCube) {
  58967. for (var face = 0; face < 6; face++) {
  58968. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  58969. // VBOs
  58970. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58971. this._effect.setFloat("face", face);
  58972. // Clear
  58973. engine.clear(scene.clearColor, true, true, true);
  58974. // Draw order
  58975. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58976. // Mipmaps
  58977. if (face === 5) {
  58978. engine.generateMipMapsForCubemap(this._texture);
  58979. }
  58980. }
  58981. }
  58982. else {
  58983. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  58984. // VBOs
  58985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58986. // Clear
  58987. engine.clear(scene.clearColor, true, true, true);
  58988. // Draw order
  58989. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58990. }
  58991. // Unbind
  58992. engine.unBindFramebuffer(this._texture, this.isCube);
  58993. if (this.onGenerated) {
  58994. this.onGenerated();
  58995. }
  58996. };
  58997. ProceduralTexture.prototype.clone = function () {
  58998. var textureSize = this.getSize();
  58999. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  59000. // Base texture
  59001. newTexture.hasAlpha = this.hasAlpha;
  59002. newTexture.level = this.level;
  59003. // RenderTarget Texture
  59004. newTexture.coordinatesMode = this.coordinatesMode;
  59005. return newTexture;
  59006. };
  59007. ProceduralTexture.prototype.dispose = function () {
  59008. var scene = this.getScene();
  59009. if (!scene) {
  59010. return;
  59011. }
  59012. var index = scene._proceduralTextures.indexOf(this);
  59013. if (index >= 0) {
  59014. scene._proceduralTextures.splice(index, 1);
  59015. }
  59016. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59017. if (vertexBuffer) {
  59018. vertexBuffer.dispose();
  59019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59020. }
  59021. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  59022. this._indexBuffer = null;
  59023. }
  59024. _super.prototype.dispose.call(this);
  59025. };
  59026. return ProceduralTexture;
  59027. }(BABYLON.Texture));
  59028. BABYLON.ProceduralTexture = ProceduralTexture;
  59029. })(BABYLON || (BABYLON = {}));
  59030. //# sourceMappingURL=babylon.proceduralTexture.js.map
  59031. var BABYLON;
  59032. (function (BABYLON) {
  59033. var CustomProceduralTexture = /** @class */ (function (_super) {
  59034. __extends(CustomProceduralTexture, _super);
  59035. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  59036. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  59037. _this._animate = true;
  59038. _this._time = 0;
  59039. _this._texturePath = texturePath;
  59040. //Try to load json
  59041. _this.loadJson(texturePath);
  59042. _this.refreshRate = 1;
  59043. return _this;
  59044. }
  59045. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  59046. var _this = this;
  59047. var noConfigFile = function () {
  59048. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  59049. try {
  59050. _this.setFragment(_this._texturePath);
  59051. }
  59052. catch (ex) {
  59053. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  59054. }
  59055. };
  59056. var configFileUrl = jsonUrl + "/config.json";
  59057. var xhr = new XMLHttpRequest();
  59058. xhr.open("GET", configFileUrl, true);
  59059. xhr.addEventListener("load", function () {
  59060. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59061. try {
  59062. _this._config = JSON.parse(xhr.response);
  59063. _this.updateShaderUniforms();
  59064. _this.updateTextures();
  59065. _this.setFragment(_this._texturePath + "/custom");
  59066. _this._animate = _this._config.animate;
  59067. _this.refreshRate = _this._config.refreshrate;
  59068. }
  59069. catch (ex) {
  59070. noConfigFile();
  59071. }
  59072. }
  59073. else {
  59074. noConfigFile();
  59075. }
  59076. }, false);
  59077. xhr.addEventListener("error", function () {
  59078. noConfigFile();
  59079. }, false);
  59080. try {
  59081. xhr.send();
  59082. }
  59083. catch (ex) {
  59084. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  59085. }
  59086. };
  59087. CustomProceduralTexture.prototype.isReady = function () {
  59088. if (!_super.prototype.isReady.call(this)) {
  59089. return false;
  59090. }
  59091. for (var name in this._textures) {
  59092. var texture = this._textures[name];
  59093. if (!texture.isReady()) {
  59094. return false;
  59095. }
  59096. }
  59097. return true;
  59098. };
  59099. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59100. var scene = this.getScene();
  59101. if (this._animate && scene) {
  59102. this._time += scene.getAnimationRatio() * 0.03;
  59103. this.updateShaderUniforms();
  59104. }
  59105. _super.prototype.render.call(this, useCameraPostProcess);
  59106. };
  59107. CustomProceduralTexture.prototype.updateTextures = function () {
  59108. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  59109. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  59110. }
  59111. };
  59112. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  59113. if (this._config) {
  59114. for (var j = 0; j < this._config.uniforms.length; j++) {
  59115. var uniform = this._config.uniforms[j];
  59116. switch (uniform.type) {
  59117. case "float":
  59118. this.setFloat(uniform.name, uniform.value);
  59119. break;
  59120. case "color3":
  59121. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  59122. break;
  59123. case "color4":
  59124. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  59125. break;
  59126. case "vector2":
  59127. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  59128. break;
  59129. case "vector3":
  59130. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  59131. break;
  59132. }
  59133. }
  59134. }
  59135. this.setFloat("time", this._time);
  59136. };
  59137. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  59138. get: function () {
  59139. return this._animate;
  59140. },
  59141. set: function (value) {
  59142. this._animate = value;
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. return CustomProceduralTexture;
  59148. }(BABYLON.ProceduralTexture));
  59149. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  59150. })(BABYLON || (BABYLON = {}));
  59151. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  59152. var BABYLON;
  59153. (function (BABYLON) {
  59154. var FreeCameraGamepadInput = /** @class */ (function () {
  59155. function FreeCameraGamepadInput() {
  59156. this.gamepadAngularSensibility = 200;
  59157. this.gamepadMoveSensibility = 40;
  59158. // private members
  59159. this._cameraTransform = BABYLON.Matrix.Identity();
  59160. this._deltaTransform = BABYLON.Vector3.Zero();
  59161. this._vector3 = BABYLON.Vector3.Zero();
  59162. this._vector2 = BABYLON.Vector2.Zero();
  59163. }
  59164. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59165. var _this = this;
  59166. var manager = this.camera.getScene().gamepadManager;
  59167. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59168. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59169. // prioritize XBOX gamepads.
  59170. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59171. _this.gamepad = gamepad;
  59172. }
  59173. }
  59174. });
  59175. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59176. if (_this.gamepad === gamepad) {
  59177. _this.gamepad = null;
  59178. }
  59179. });
  59180. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59181. };
  59182. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59183. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59184. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59185. this.gamepad = null;
  59186. };
  59187. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59188. if (this.gamepad && this.gamepad.leftStick) {
  59189. var camera = this.camera;
  59190. var LSValues = this.gamepad.leftStick;
  59191. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59192. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59193. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59194. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59195. var RSValues = this.gamepad.rightStick;
  59196. if (RSValues) {
  59197. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59198. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59199. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59200. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59201. }
  59202. else {
  59203. RSValues = { x: 0, y: 0 };
  59204. }
  59205. if (!camera.rotationQuaternion) {
  59206. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59207. }
  59208. else {
  59209. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59210. }
  59211. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59212. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59213. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59214. camera.cameraDirection.addInPlace(this._deltaTransform);
  59215. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59216. camera.cameraRotation.addInPlace(this._vector2);
  59217. }
  59218. };
  59219. FreeCameraGamepadInput.prototype.getClassName = function () {
  59220. return "FreeCameraGamepadInput";
  59221. };
  59222. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59223. return "gamepad";
  59224. };
  59225. __decorate([
  59226. BABYLON.serialize()
  59227. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59228. __decorate([
  59229. BABYLON.serialize()
  59230. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59231. return FreeCameraGamepadInput;
  59232. }());
  59233. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59234. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59235. })(BABYLON || (BABYLON = {}));
  59236. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59237. var BABYLON;
  59238. (function (BABYLON) {
  59239. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59240. function ArcRotateCameraGamepadInput() {
  59241. this.gamepadRotationSensibility = 80;
  59242. this.gamepadMoveSensibility = 40;
  59243. }
  59244. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59245. var _this = this;
  59246. var manager = this.camera.getScene().gamepadManager;
  59247. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59248. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59249. // prioritize XBOX gamepads.
  59250. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59251. _this.gamepad = gamepad;
  59252. }
  59253. }
  59254. });
  59255. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59256. if (_this.gamepad === gamepad) {
  59257. _this.gamepad = null;
  59258. }
  59259. });
  59260. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59261. };
  59262. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59263. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59264. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59265. this.gamepad = null;
  59266. };
  59267. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59268. if (this.gamepad) {
  59269. var camera = this.camera;
  59270. var RSValues = this.gamepad.rightStick;
  59271. if (RSValues) {
  59272. if (RSValues.x != 0) {
  59273. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59274. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59275. camera.inertialAlphaOffset += normalizedRX;
  59276. }
  59277. }
  59278. if (RSValues.y != 0) {
  59279. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59280. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59281. camera.inertialBetaOffset += normalizedRY;
  59282. }
  59283. }
  59284. }
  59285. var LSValues = this.gamepad.leftStick;
  59286. if (LSValues && LSValues.y != 0) {
  59287. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59288. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59289. this.camera.inertialRadiusOffset -= normalizedLY;
  59290. }
  59291. }
  59292. }
  59293. };
  59294. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59295. return "ArcRotateCameraGamepadInput";
  59296. };
  59297. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59298. return "gamepad";
  59299. };
  59300. __decorate([
  59301. BABYLON.serialize()
  59302. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59303. __decorate([
  59304. BABYLON.serialize()
  59305. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59306. return ArcRotateCameraGamepadInput;
  59307. }());
  59308. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59309. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59310. })(BABYLON || (BABYLON = {}));
  59311. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59312. var BABYLON;
  59313. (function (BABYLON) {
  59314. var GamepadManager = /** @class */ (function () {
  59315. function GamepadManager(_scene) {
  59316. var _this = this;
  59317. this._scene = _scene;
  59318. this._babylonGamepads = [];
  59319. this._oneGamepadConnected = false;
  59320. this._isMonitoring = false;
  59321. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59322. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59323. this._gamepadEventSupported = false;
  59324. }
  59325. else {
  59326. this._gamepadEventSupported = 'GamepadEvent' in window;
  59327. this._gamepadSupport = (navigator.getGamepads ||
  59328. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59329. }
  59330. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59331. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59332. for (var i in _this._babylonGamepads) {
  59333. var gamepad = _this._babylonGamepads[i];
  59334. if (gamepad && gamepad._isConnected) {
  59335. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59336. }
  59337. }
  59338. });
  59339. this._onGamepadConnectedEvent = function (evt) {
  59340. var gamepad = evt.gamepad;
  59341. if (gamepad.index in _this._babylonGamepads) {
  59342. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59343. return;
  59344. }
  59345. }
  59346. var newGamepad;
  59347. if (_this._babylonGamepads[gamepad.index]) {
  59348. newGamepad = _this._babylonGamepads[gamepad.index];
  59349. newGamepad.browserGamepad = gamepad;
  59350. newGamepad._isConnected = true;
  59351. }
  59352. else {
  59353. newGamepad = _this._addNewGamepad(gamepad);
  59354. }
  59355. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59356. _this._startMonitoringGamepads();
  59357. };
  59358. this._onGamepadDisconnectedEvent = function (evt) {
  59359. var gamepad = evt.gamepad;
  59360. // Remove the gamepad from the list of gamepads to monitor.
  59361. for (var i in _this._babylonGamepads) {
  59362. if (_this._babylonGamepads[i].index === gamepad.index) {
  59363. var disconnectedGamepad = _this._babylonGamepads[i];
  59364. disconnectedGamepad._isConnected = false;
  59365. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59366. break;
  59367. }
  59368. }
  59369. };
  59370. if (this._gamepadSupport) {
  59371. //first add already-connected gamepads
  59372. this._updateGamepadObjects();
  59373. if (this._babylonGamepads.length) {
  59374. this._startMonitoringGamepads();
  59375. }
  59376. // Checking if the gamepad connected event is supported (like in Firefox)
  59377. if (this._gamepadEventSupported) {
  59378. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59379. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59380. }
  59381. else {
  59382. this._startMonitoringGamepads();
  59383. }
  59384. }
  59385. }
  59386. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59387. get: function () {
  59388. return this._babylonGamepads;
  59389. },
  59390. enumerable: true,
  59391. configurable: true
  59392. });
  59393. GamepadManager.prototype.getGamepadByType = function (type) {
  59394. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59395. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59396. var gamepad = _a[_i];
  59397. if (gamepad && gamepad.type === type) {
  59398. return gamepad;
  59399. }
  59400. }
  59401. return null;
  59402. };
  59403. GamepadManager.prototype.dispose = function () {
  59404. if (this._gamepadEventSupported) {
  59405. if (this._onGamepadConnectedEvent) {
  59406. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59407. }
  59408. if (this._onGamepadDisconnectedEvent) {
  59409. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  59410. }
  59411. this._onGamepadConnectedEvent = null;
  59412. this._onGamepadDisconnectedEvent = null;
  59413. }
  59414. this._babylonGamepads.forEach(function (gamepad) {
  59415. gamepad.dispose();
  59416. });
  59417. this.onGamepadConnectedObservable.clear();
  59418. this.onGamepadDisconnectedObservable.clear();
  59419. this._oneGamepadConnected = false;
  59420. this._stopMonitoringGamepads();
  59421. this._babylonGamepads = [];
  59422. };
  59423. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  59424. if (!this._oneGamepadConnected) {
  59425. this._oneGamepadConnected = true;
  59426. }
  59427. var newGamepad;
  59428. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  59429. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  59430. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  59431. }
  59432. else if (gamepad.pose) {
  59433. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  59434. }
  59435. else {
  59436. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  59437. }
  59438. this._babylonGamepads[newGamepad.index] = newGamepad;
  59439. return newGamepad;
  59440. };
  59441. GamepadManager.prototype._startMonitoringGamepads = function () {
  59442. if (!this._isMonitoring) {
  59443. this._isMonitoring = true;
  59444. //back-comp
  59445. if (!this._scene) {
  59446. this._checkGamepadsStatus();
  59447. }
  59448. }
  59449. };
  59450. GamepadManager.prototype._stopMonitoringGamepads = function () {
  59451. this._isMonitoring = false;
  59452. };
  59453. GamepadManager.prototype._checkGamepadsStatus = function () {
  59454. var _this = this;
  59455. // Hack to be compatible Chrome
  59456. this._updateGamepadObjects();
  59457. for (var i in this._babylonGamepads) {
  59458. var gamepad = this._babylonGamepads[i];
  59459. if (!gamepad || !gamepad.isConnected) {
  59460. continue;
  59461. }
  59462. gamepad.update();
  59463. }
  59464. if (this._isMonitoring && !this._scene) {
  59465. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  59466. }
  59467. };
  59468. // This function is called only on Chrome, which does not properly support
  59469. // connection/disconnection events and forces you to recopy again the gamepad object
  59470. GamepadManager.prototype._updateGamepadObjects = function () {
  59471. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  59472. for (var i = 0; i < gamepads.length; i++) {
  59473. if (gamepads[i]) {
  59474. if (!this._babylonGamepads[gamepads[i].index]) {
  59475. var newGamepad = this._addNewGamepad(gamepads[i]);
  59476. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59477. }
  59478. else {
  59479. // Forced to copy again this object for Chrome for unknown reason
  59480. this._babylonGamepads[i].browserGamepad = gamepads[i];
  59481. if (!this._babylonGamepads[i].isConnected) {
  59482. this._babylonGamepads[i]._isConnected = true;
  59483. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  59484. }
  59485. }
  59486. }
  59487. }
  59488. };
  59489. return GamepadManager;
  59490. }());
  59491. BABYLON.GamepadManager = GamepadManager;
  59492. })(BABYLON || (BABYLON = {}));
  59493. //# sourceMappingURL=babylon.gamepadManager.js.map
  59494. var BABYLON;
  59495. (function (BABYLON) {
  59496. var StickValues = /** @class */ (function () {
  59497. function StickValues(x, y) {
  59498. this.x = x;
  59499. this.y = y;
  59500. }
  59501. return StickValues;
  59502. }());
  59503. BABYLON.StickValues = StickValues;
  59504. var Gamepad = /** @class */ (function () {
  59505. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  59506. if (leftStickX === void 0) { leftStickX = 0; }
  59507. if (leftStickY === void 0) { leftStickY = 1; }
  59508. if (rightStickX === void 0) { rightStickX = 2; }
  59509. if (rightStickY === void 0) { rightStickY = 3; }
  59510. this.id = id;
  59511. this.index = index;
  59512. this.browserGamepad = browserGamepad;
  59513. this._isConnected = true;
  59514. this._invertLeftStickY = false;
  59515. this.type = Gamepad.GAMEPAD;
  59516. this._leftStickAxisX = leftStickX;
  59517. this._leftStickAxisY = leftStickY;
  59518. this._rightStickAxisX = rightStickX;
  59519. this._rightStickAxisY = rightStickY;
  59520. if (this.browserGamepad.axes.length >= 2) {
  59521. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59522. }
  59523. if (this.browserGamepad.axes.length >= 4) {
  59524. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59525. }
  59526. }
  59527. Object.defineProperty(Gamepad.prototype, "isConnected", {
  59528. get: function () {
  59529. return this._isConnected;
  59530. },
  59531. enumerable: true,
  59532. configurable: true
  59533. });
  59534. Gamepad.prototype.onleftstickchanged = function (callback) {
  59535. this._onleftstickchanged = callback;
  59536. };
  59537. Gamepad.prototype.onrightstickchanged = function (callback) {
  59538. this._onrightstickchanged = callback;
  59539. };
  59540. Object.defineProperty(Gamepad.prototype, "leftStick", {
  59541. get: function () {
  59542. return this._leftStick;
  59543. },
  59544. set: function (newValues) {
  59545. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  59546. this._onleftstickchanged(newValues);
  59547. }
  59548. this._leftStick = newValues;
  59549. },
  59550. enumerable: true,
  59551. configurable: true
  59552. });
  59553. Object.defineProperty(Gamepad.prototype, "rightStick", {
  59554. get: function () {
  59555. return this._rightStick;
  59556. },
  59557. set: function (newValues) {
  59558. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  59559. this._onrightstickchanged(newValues);
  59560. }
  59561. this._rightStick = newValues;
  59562. },
  59563. enumerable: true,
  59564. configurable: true
  59565. });
  59566. Gamepad.prototype.update = function () {
  59567. if (this._leftStick) {
  59568. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59569. if (this._invertLeftStickY) {
  59570. this.leftStick.y *= -1;
  59571. }
  59572. }
  59573. if (this._rightStick) {
  59574. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59575. }
  59576. };
  59577. Gamepad.prototype.dispose = function () {
  59578. };
  59579. Gamepad.GAMEPAD = 0;
  59580. Gamepad.GENERIC = 1;
  59581. Gamepad.XBOX = 2;
  59582. Gamepad.POSE_ENABLED = 3;
  59583. return Gamepad;
  59584. }());
  59585. BABYLON.Gamepad = Gamepad;
  59586. var GenericPad = /** @class */ (function (_super) {
  59587. __extends(GenericPad, _super);
  59588. function GenericPad(id, index, browserGamepad) {
  59589. var _this = _super.call(this, id, index, browserGamepad) || this;
  59590. _this.onButtonDownObservable = new BABYLON.Observable();
  59591. _this.onButtonUpObservable = new BABYLON.Observable();
  59592. _this.type = Gamepad.GENERIC;
  59593. _this._buttons = new Array(browserGamepad.buttons.length);
  59594. return _this;
  59595. }
  59596. GenericPad.prototype.onbuttondown = function (callback) {
  59597. this._onbuttondown = callback;
  59598. };
  59599. GenericPad.prototype.onbuttonup = function (callback) {
  59600. this._onbuttonup = callback;
  59601. };
  59602. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  59603. if (newValue !== currentValue) {
  59604. if (newValue === 1) {
  59605. if (this._onbuttondown) {
  59606. this._onbuttondown(buttonIndex);
  59607. }
  59608. this.onButtonDownObservable.notifyObservers(buttonIndex);
  59609. }
  59610. if (newValue === 0) {
  59611. if (this._onbuttonup) {
  59612. this._onbuttonup(buttonIndex);
  59613. }
  59614. this.onButtonUpObservable.notifyObservers(buttonIndex);
  59615. }
  59616. }
  59617. return newValue;
  59618. };
  59619. GenericPad.prototype.update = function () {
  59620. _super.prototype.update.call(this);
  59621. for (var index = 0; index < this._buttons.length; index++) {
  59622. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  59623. }
  59624. };
  59625. GenericPad.prototype.dispose = function () {
  59626. _super.prototype.dispose.call(this);
  59627. this.onButtonDownObservable.clear();
  59628. this.onButtonUpObservable.clear();
  59629. };
  59630. return GenericPad;
  59631. }(Gamepad));
  59632. BABYLON.GenericPad = GenericPad;
  59633. })(BABYLON || (BABYLON = {}));
  59634. //# sourceMappingURL=babylon.gamepad.js.map
  59635. var BABYLON;
  59636. (function (BABYLON) {
  59637. var Xbox360Button;
  59638. (function (Xbox360Button) {
  59639. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  59640. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  59641. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  59642. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  59643. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  59644. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  59645. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  59646. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  59647. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  59648. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  59649. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  59650. var Xbox360Dpad;
  59651. (function (Xbox360Dpad) {
  59652. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  59653. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  59654. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  59655. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  59656. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  59657. var Xbox360Pad = /** @class */ (function (_super) {
  59658. __extends(Xbox360Pad, _super);
  59659. function Xbox360Pad(id, index, gamepad, xboxOne) {
  59660. if (xboxOne === void 0) { xboxOne = false; }
  59661. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  59662. _this._leftTrigger = 0;
  59663. _this._rightTrigger = 0;
  59664. _this.onButtonDownObservable = new BABYLON.Observable();
  59665. _this.onButtonUpObservable = new BABYLON.Observable();
  59666. _this.onPadDownObservable = new BABYLON.Observable();
  59667. _this.onPadUpObservable = new BABYLON.Observable();
  59668. _this._buttonA = 0;
  59669. _this._buttonB = 0;
  59670. _this._buttonX = 0;
  59671. _this._buttonY = 0;
  59672. _this._buttonBack = 0;
  59673. _this._buttonStart = 0;
  59674. _this._buttonLB = 0;
  59675. _this._buttonRB = 0;
  59676. _this._buttonLeftStick = 0;
  59677. _this._buttonRightStick = 0;
  59678. _this._dPadUp = 0;
  59679. _this._dPadDown = 0;
  59680. _this._dPadLeft = 0;
  59681. _this._dPadRight = 0;
  59682. _this._isXboxOnePad = false;
  59683. _this.type = BABYLON.Gamepad.XBOX;
  59684. _this._isXboxOnePad = xboxOne;
  59685. return _this;
  59686. }
  59687. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  59688. this._onlefttriggerchanged = callback;
  59689. };
  59690. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  59691. this._onrighttriggerchanged = callback;
  59692. };
  59693. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  59694. get: function () {
  59695. return this._leftTrigger;
  59696. },
  59697. set: function (newValue) {
  59698. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  59699. this._onlefttriggerchanged(newValue);
  59700. }
  59701. this._leftTrigger = newValue;
  59702. },
  59703. enumerable: true,
  59704. configurable: true
  59705. });
  59706. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  59707. get: function () {
  59708. return this._rightTrigger;
  59709. },
  59710. set: function (newValue) {
  59711. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  59712. this._onrighttriggerchanged(newValue);
  59713. }
  59714. this._rightTrigger = newValue;
  59715. },
  59716. enumerable: true,
  59717. configurable: true
  59718. });
  59719. Xbox360Pad.prototype.onbuttondown = function (callback) {
  59720. this._onbuttondown = callback;
  59721. };
  59722. Xbox360Pad.prototype.onbuttonup = function (callback) {
  59723. this._onbuttonup = callback;
  59724. };
  59725. Xbox360Pad.prototype.ondpaddown = function (callback) {
  59726. this._ondpaddown = callback;
  59727. };
  59728. Xbox360Pad.prototype.ondpadup = function (callback) {
  59729. this._ondpadup = callback;
  59730. };
  59731. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  59732. if (newValue !== currentValue) {
  59733. if (newValue === 1) {
  59734. if (this._onbuttondown) {
  59735. this._onbuttondown(buttonType);
  59736. }
  59737. this.onButtonDownObservable.notifyObservers(buttonType);
  59738. }
  59739. if (newValue === 0) {
  59740. if (this._onbuttonup) {
  59741. this._onbuttonup(buttonType);
  59742. }
  59743. this.onButtonUpObservable.notifyObservers(buttonType);
  59744. }
  59745. }
  59746. return newValue;
  59747. };
  59748. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  59749. if (newValue !== currentValue) {
  59750. if (newValue === 1) {
  59751. if (this._ondpaddown) {
  59752. this._ondpaddown(buttonType);
  59753. }
  59754. this.onPadDownObservable.notifyObservers(buttonType);
  59755. }
  59756. if (newValue === 0) {
  59757. if (this._ondpadup) {
  59758. this._ondpadup(buttonType);
  59759. }
  59760. this.onPadUpObservable.notifyObservers(buttonType);
  59761. }
  59762. }
  59763. return newValue;
  59764. };
  59765. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  59766. get: function () {
  59767. return this._buttonA;
  59768. },
  59769. set: function (value) {
  59770. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  59771. },
  59772. enumerable: true,
  59773. configurable: true
  59774. });
  59775. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  59776. get: function () {
  59777. return this._buttonB;
  59778. },
  59779. set: function (value) {
  59780. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  59781. },
  59782. enumerable: true,
  59783. configurable: true
  59784. });
  59785. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  59786. get: function () {
  59787. return this._buttonX;
  59788. },
  59789. set: function (value) {
  59790. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  59791. },
  59792. enumerable: true,
  59793. configurable: true
  59794. });
  59795. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  59796. get: function () {
  59797. return this._buttonY;
  59798. },
  59799. set: function (value) {
  59800. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  59801. },
  59802. enumerable: true,
  59803. configurable: true
  59804. });
  59805. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  59806. get: function () {
  59807. return this._buttonStart;
  59808. },
  59809. set: function (value) {
  59810. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  59811. },
  59812. enumerable: true,
  59813. configurable: true
  59814. });
  59815. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  59816. get: function () {
  59817. return this._buttonBack;
  59818. },
  59819. set: function (value) {
  59820. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  59821. },
  59822. enumerable: true,
  59823. configurable: true
  59824. });
  59825. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  59826. get: function () {
  59827. return this._buttonLB;
  59828. },
  59829. set: function (value) {
  59830. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  59831. },
  59832. enumerable: true,
  59833. configurable: true
  59834. });
  59835. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  59836. get: function () {
  59837. return this._buttonRB;
  59838. },
  59839. set: function (value) {
  59840. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  59841. },
  59842. enumerable: true,
  59843. configurable: true
  59844. });
  59845. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  59846. get: function () {
  59847. return this._buttonLeftStick;
  59848. },
  59849. set: function (value) {
  59850. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  59851. },
  59852. enumerable: true,
  59853. configurable: true
  59854. });
  59855. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  59856. get: function () {
  59857. return this._buttonRightStick;
  59858. },
  59859. set: function (value) {
  59860. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  59861. },
  59862. enumerable: true,
  59863. configurable: true
  59864. });
  59865. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  59866. get: function () {
  59867. return this._dPadUp;
  59868. },
  59869. set: function (value) {
  59870. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  59871. },
  59872. enumerable: true,
  59873. configurable: true
  59874. });
  59875. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  59876. get: function () {
  59877. return this._dPadDown;
  59878. },
  59879. set: function (value) {
  59880. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  59881. },
  59882. enumerable: true,
  59883. configurable: true
  59884. });
  59885. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  59886. get: function () {
  59887. return this._dPadLeft;
  59888. },
  59889. set: function (value) {
  59890. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  59891. },
  59892. enumerable: true,
  59893. configurable: true
  59894. });
  59895. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  59896. get: function () {
  59897. return this._dPadRight;
  59898. },
  59899. set: function (value) {
  59900. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  59901. },
  59902. enumerable: true,
  59903. configurable: true
  59904. });
  59905. Xbox360Pad.prototype.update = function () {
  59906. _super.prototype.update.call(this);
  59907. if (this._isXboxOnePad) {
  59908. this.buttonA = this.browserGamepad.buttons[0].value;
  59909. this.buttonB = this.browserGamepad.buttons[1].value;
  59910. this.buttonX = this.browserGamepad.buttons[2].value;
  59911. this.buttonY = this.browserGamepad.buttons[3].value;
  59912. this.buttonLB = this.browserGamepad.buttons[4].value;
  59913. this.buttonRB = this.browserGamepad.buttons[5].value;
  59914. this.leftTrigger = this.browserGamepad.axes[2];
  59915. this.rightTrigger = this.browserGamepad.axes[5];
  59916. this.buttonBack = this.browserGamepad.buttons[9].value;
  59917. this.buttonStart = this.browserGamepad.buttons[8].value;
  59918. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  59919. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  59920. this.dPadUp = this.browserGamepad.buttons[11].value;
  59921. this.dPadDown = this.browserGamepad.buttons[12].value;
  59922. this.dPadLeft = this.browserGamepad.buttons[13].value;
  59923. this.dPadRight = this.browserGamepad.buttons[14].value;
  59924. }
  59925. else {
  59926. this.buttonA = this.browserGamepad.buttons[0].value;
  59927. this.buttonB = this.browserGamepad.buttons[1].value;
  59928. this.buttonX = this.browserGamepad.buttons[2].value;
  59929. this.buttonY = this.browserGamepad.buttons[3].value;
  59930. this.buttonLB = this.browserGamepad.buttons[4].value;
  59931. this.buttonRB = this.browserGamepad.buttons[5].value;
  59932. this.leftTrigger = this.browserGamepad.buttons[6].value;
  59933. this.rightTrigger = this.browserGamepad.buttons[7].value;
  59934. this.buttonBack = this.browserGamepad.buttons[8].value;
  59935. this.buttonStart = this.browserGamepad.buttons[9].value;
  59936. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  59937. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  59938. this.dPadUp = this.browserGamepad.buttons[12].value;
  59939. this.dPadDown = this.browserGamepad.buttons[13].value;
  59940. this.dPadLeft = this.browserGamepad.buttons[14].value;
  59941. this.dPadRight = this.browserGamepad.buttons[15].value;
  59942. }
  59943. };
  59944. Xbox360Pad.prototype.dispose = function () {
  59945. _super.prototype.dispose.call(this);
  59946. this.onButtonDownObservable.clear();
  59947. this.onButtonUpObservable.clear();
  59948. this.onPadDownObservable.clear();
  59949. this.onPadUpObservable.clear();
  59950. };
  59951. return Xbox360Pad;
  59952. }(BABYLON.Gamepad));
  59953. BABYLON.Xbox360Pad = Xbox360Pad;
  59954. })(BABYLON || (BABYLON = {}));
  59955. //# sourceMappingURL=babylon.xboxGamepad.js.map
  59956. var BABYLON;
  59957. (function (BABYLON) {
  59958. var PoseEnabledControllerType;
  59959. (function (PoseEnabledControllerType) {
  59960. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  59961. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  59962. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  59963. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  59964. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  59965. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  59966. var PoseEnabledControllerHelper = /** @class */ (function () {
  59967. function PoseEnabledControllerHelper() {
  59968. }
  59969. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  59970. // Oculus Touch
  59971. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  59972. return new BABYLON.OculusTouchController(vrGamepad);
  59973. }
  59974. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  59975. return new BABYLON.WindowsMotionController(vrGamepad);
  59976. }
  59977. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  59978. return new BABYLON.ViveController(vrGamepad);
  59979. }
  59980. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  59981. return new BABYLON.GearVRController(vrGamepad);
  59982. }
  59983. else {
  59984. return new BABYLON.GenericController(vrGamepad);
  59985. }
  59986. };
  59987. return PoseEnabledControllerHelper;
  59988. }());
  59989. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  59990. var PoseEnabledController = /** @class */ (function (_super) {
  59991. __extends(PoseEnabledController, _super);
  59992. function PoseEnabledController(browserGamepad) {
  59993. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  59994. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  59995. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  59996. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  59997. // Represents device position and rotation in babylon space
  59998. _this.devicePosition = BABYLON.Vector3.Zero();
  59999. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  60000. _this.deviceScaleFactor = 1;
  60001. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  60002. _this._deviceToWorld = BABYLON.Matrix.Identity();
  60003. _this._workingMatrix = BABYLON.Matrix.Identity();
  60004. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  60005. _this.controllerType = PoseEnabledControllerType.GENERIC;
  60006. _this.position = BABYLON.Vector3.Zero();
  60007. _this.rotationQuaternion = new BABYLON.Quaternion();
  60008. _this._calculatedPosition = BABYLON.Vector3.Zero();
  60009. _this._calculatedRotation = new BABYLON.Quaternion();
  60010. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  60011. return _this;
  60012. }
  60013. PoseEnabledController.prototype.update = function () {
  60014. _super.prototype.update.call(this);
  60015. var pose = this.browserGamepad.pose;
  60016. this.updateFromDevice(pose);
  60017. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  60018. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  60019. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  60020. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  60021. if (this._mesh) {
  60022. this._mesh.position.copyFrom(this.devicePosition);
  60023. if (this._mesh.rotationQuaternion) {
  60024. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  60025. }
  60026. }
  60027. };
  60028. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  60029. if (poseData) {
  60030. this.rawPose = poseData;
  60031. if (poseData.position) {
  60032. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  60033. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  60034. this._deviceRoomPosition.z *= -1;
  60035. }
  60036. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  60037. this._calculatedPosition.addInPlace(this.position);
  60038. }
  60039. var pose = this.rawPose;
  60040. if (poseData.orientation && pose.orientation) {
  60041. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  60042. if (this._mesh) {
  60043. if (this._mesh.getScene().useRightHandedSystem) {
  60044. this._deviceRoomRotationQuaternion.z *= -1;
  60045. this._deviceRoomRotationQuaternion.w *= -1;
  60046. }
  60047. else {
  60048. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  60049. }
  60050. }
  60051. // if the camera is set, rotate to the camera's rotation
  60052. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  60053. }
  60054. }
  60055. };
  60056. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  60057. if (this._mesh) {
  60058. this._mesh.parent = null;
  60059. }
  60060. this._mesh = mesh;
  60061. if (this._poseControlledCamera) {
  60062. this._mesh.parent = this._poseControlledCamera;
  60063. }
  60064. if (!this._mesh.rotationQuaternion) {
  60065. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  60066. }
  60067. };
  60068. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  60069. this._poseControlledCamera = camera;
  60070. if (this._mesh) {
  60071. this._mesh.parent = this._poseControlledCamera;
  60072. }
  60073. };
  60074. PoseEnabledController.prototype.dispose = function () {
  60075. if (this._mesh) {
  60076. this._mesh.dispose();
  60077. }
  60078. this._mesh = null;
  60079. _super.prototype.dispose.call(this);
  60080. };
  60081. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  60082. get: function () {
  60083. return this._mesh;
  60084. },
  60085. enumerable: true,
  60086. configurable: true
  60087. });
  60088. PoseEnabledController.prototype.getForwardRay = function (length) {
  60089. if (length === void 0) { length = 100; }
  60090. if (!this.mesh) {
  60091. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  60092. }
  60093. var m = this.mesh.getWorldMatrix();
  60094. var origin = m.getTranslation();
  60095. var forward = new BABYLON.Vector3(0, 0, -1);
  60096. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60097. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60098. return new BABYLON.Ray(origin, direction, length);
  60099. };
  60100. return PoseEnabledController;
  60101. }(BABYLON.Gamepad));
  60102. BABYLON.PoseEnabledController = PoseEnabledController;
  60103. })(BABYLON || (BABYLON = {}));
  60104. //# sourceMappingURL=babylon.poseEnabledController.js.map
  60105. var BABYLON;
  60106. (function (BABYLON) {
  60107. var WebVRController = /** @class */ (function (_super) {
  60108. __extends(WebVRController, _super);
  60109. function WebVRController(vrGamepad) {
  60110. var _this = _super.call(this, vrGamepad) || this;
  60111. // Observables
  60112. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  60113. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  60114. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  60115. _this.onPadStateChangedObservable = new BABYLON.Observable();
  60116. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  60117. _this.pad = { x: 0, y: 0 };
  60118. // avoid GC, store state in a tmp object
  60119. _this._changes = {
  60120. pressChanged: false,
  60121. touchChanged: false,
  60122. valueChanged: false,
  60123. changed: false
  60124. };
  60125. _this._buttons = new Array(vrGamepad.buttons.length);
  60126. _this.hand = vrGamepad.hand;
  60127. return _this;
  60128. }
  60129. WebVRController.prototype.onButtonStateChange = function (callback) {
  60130. this._onButtonStateChange = callback;
  60131. };
  60132. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  60133. get: function () {
  60134. return this._defaultModel;
  60135. },
  60136. enumerable: true,
  60137. configurable: true
  60138. });
  60139. WebVRController.prototype.update = function () {
  60140. _super.prototype.update.call(this);
  60141. for (var index = 0; index < this._buttons.length; index++) {
  60142. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  60143. }
  60144. ;
  60145. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  60146. this.pad.x = this.leftStick.x;
  60147. this.pad.y = this.leftStick.y;
  60148. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  60149. }
  60150. };
  60151. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  60152. if (!newState) {
  60153. newState = {
  60154. pressed: false,
  60155. touched: false,
  60156. value: 0
  60157. };
  60158. }
  60159. if (!currentState) {
  60160. this._buttons[buttonIndex] = {
  60161. pressed: newState.pressed,
  60162. touched: newState.touched,
  60163. value: newState.value
  60164. };
  60165. return;
  60166. }
  60167. this._checkChanges(newState, currentState);
  60168. if (this._changes.changed) {
  60169. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  60170. this.handleButtonChange(buttonIndex, newState, this._changes);
  60171. }
  60172. this._buttons[buttonIndex].pressed = newState.pressed;
  60173. this._buttons[buttonIndex].touched = newState.touched;
  60174. // oculus triggers are never 0, thou not touched.
  60175. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60176. };
  60177. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60178. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60179. this._changes.touchChanged = newState.touched !== currentState.touched;
  60180. this._changes.valueChanged = newState.value !== currentState.value;
  60181. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60182. return this._changes;
  60183. };
  60184. WebVRController.prototype.dispose = function () {
  60185. _super.prototype.dispose.call(this);
  60186. this.onTriggerStateChangedObservable.clear();
  60187. this.onMainButtonStateChangedObservable.clear();
  60188. this.onSecondaryButtonStateChangedObservable.clear();
  60189. this.onPadStateChangedObservable.clear();
  60190. this.onPadValuesChangedObservable.clear();
  60191. };
  60192. return WebVRController;
  60193. }(BABYLON.PoseEnabledController));
  60194. BABYLON.WebVRController = WebVRController;
  60195. })(BABYLON || (BABYLON = {}));
  60196. //# sourceMappingURL=babylon.webVRController.js.map
  60197. var BABYLON;
  60198. (function (BABYLON) {
  60199. var OculusTouchController = /** @class */ (function (_super) {
  60200. __extends(OculusTouchController, _super);
  60201. function OculusTouchController(vrGamepad) {
  60202. var _this = _super.call(this, vrGamepad) || this;
  60203. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60204. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60205. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60206. return _this;
  60207. }
  60208. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60209. var _this = this;
  60210. var meshName;
  60211. // Hand
  60212. if (this.hand === 'left') {
  60213. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60214. }
  60215. else {
  60216. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60217. }
  60218. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60219. /*
  60220. Parent Mesh name: oculus_touch_left
  60221. - body
  60222. - trigger
  60223. - thumbstick
  60224. - grip
  60225. - button_y
  60226. - button_x
  60227. - button_enter
  60228. */
  60229. _this._defaultModel = newMeshes[1];
  60230. _this.attachToMesh(_this._defaultModel);
  60231. if (meshLoaded) {
  60232. meshLoaded(_this._defaultModel);
  60233. }
  60234. });
  60235. };
  60236. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60237. // helper getters for left and right hand.
  60238. get: function () {
  60239. if (this.hand === 'right') {
  60240. return this.onMainButtonStateChangedObservable;
  60241. }
  60242. else {
  60243. throw new Error('No A button on left hand');
  60244. }
  60245. },
  60246. enumerable: true,
  60247. configurable: true
  60248. });
  60249. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60250. get: function () {
  60251. if (this.hand === 'right') {
  60252. return this.onSecondaryButtonStateChangedObservable;
  60253. }
  60254. else {
  60255. throw new Error('No B button on left hand');
  60256. }
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60262. get: function () {
  60263. if (this.hand === 'left') {
  60264. return this.onMainButtonStateChangedObservable;
  60265. }
  60266. else {
  60267. throw new Error('No X button on right hand');
  60268. }
  60269. },
  60270. enumerable: true,
  60271. configurable: true
  60272. });
  60273. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60274. get: function () {
  60275. if (this.hand === 'left') {
  60276. return this.onSecondaryButtonStateChangedObservable;
  60277. }
  60278. else {
  60279. throw new Error('No Y button on right hand');
  60280. }
  60281. },
  60282. enumerable: true,
  60283. configurable: true
  60284. });
  60285. /*
  60286. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60287. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60288. 2) secondary trigger (same)
  60289. 3) A (right) X (left), touch, pressed = value
  60290. 4) B / Y
  60291. 5) thumb rest
  60292. */
  60293. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60294. var notifyObject = state; //{ state: state, changes: changes };
  60295. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60296. switch (buttonIdx) {
  60297. case 0:
  60298. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60299. return;
  60300. case 1:// index trigger
  60301. if (this._defaultModel) {
  60302. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60303. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60304. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60305. }
  60306. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60307. return;
  60308. case 2:// secondary trigger
  60309. if (this._defaultModel) {
  60310. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60311. }
  60312. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60313. return;
  60314. case 3:
  60315. if (this._defaultModel) {
  60316. if (notifyObject.pressed) {
  60317. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60318. }
  60319. else {
  60320. (this._defaultModel.getChildren()[1]).position.y = 0;
  60321. }
  60322. }
  60323. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60324. return;
  60325. case 4:
  60326. if (this._defaultModel) {
  60327. if (notifyObject.pressed) {
  60328. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60329. }
  60330. else {
  60331. (this._defaultModel.getChildren()[2]).position.y = 0;
  60332. }
  60333. }
  60334. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60335. return;
  60336. case 5:
  60337. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60338. return;
  60339. }
  60340. };
  60341. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60342. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60343. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60344. return OculusTouchController;
  60345. }(BABYLON.WebVRController));
  60346. BABYLON.OculusTouchController = OculusTouchController;
  60347. })(BABYLON || (BABYLON = {}));
  60348. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60349. var BABYLON;
  60350. (function (BABYLON) {
  60351. var ViveController = /** @class */ (function (_super) {
  60352. __extends(ViveController, _super);
  60353. function ViveController(vrGamepad) {
  60354. var _this = _super.call(this, vrGamepad) || this;
  60355. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60356. _this._invertLeftStickY = true;
  60357. return _this;
  60358. }
  60359. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60360. var _this = this;
  60361. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60362. /*
  60363. Parent Mesh name: ViveWand
  60364. - body
  60365. - r_gripper
  60366. - l_gripper
  60367. - menu_button
  60368. - system_button
  60369. - trackpad
  60370. - trigger
  60371. - LED
  60372. */
  60373. _this._defaultModel = newMeshes[1];
  60374. _this.attachToMesh(_this._defaultModel);
  60375. if (meshLoaded) {
  60376. meshLoaded(_this._defaultModel);
  60377. }
  60378. });
  60379. };
  60380. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60381. get: function () {
  60382. return this.onMainButtonStateChangedObservable;
  60383. },
  60384. enumerable: true,
  60385. configurable: true
  60386. });
  60387. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60388. get: function () {
  60389. return this.onMainButtonStateChangedObservable;
  60390. },
  60391. enumerable: true,
  60392. configurable: true
  60393. });
  60394. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60395. get: function () {
  60396. return this.onSecondaryButtonStateChangedObservable;
  60397. },
  60398. enumerable: true,
  60399. configurable: true
  60400. });
  60401. /**
  60402. * Vive mapping:
  60403. * 0: touchpad
  60404. * 1: trigger
  60405. * 2: left AND right buttons
  60406. * 3: menu button
  60407. */
  60408. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60409. var notifyObject = state; //{ state: state, changes: changes };
  60410. switch (buttonIdx) {
  60411. case 0:
  60412. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60413. return;
  60414. case 1:// index trigger
  60415. if (this._defaultModel) {
  60416. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  60417. }
  60418. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60419. return;
  60420. case 2:// left AND right button
  60421. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60422. return;
  60423. case 3:
  60424. if (this._defaultModel) {
  60425. if (notifyObject.pressed) {
  60426. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60427. }
  60428. else {
  60429. (this._defaultModel.getChildren()[2]).position.y = 0;
  60430. }
  60431. }
  60432. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60433. return;
  60434. }
  60435. };
  60436. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  60437. ViveController.MODEL_FILENAME = 'wand.babylon';
  60438. return ViveController;
  60439. }(BABYLON.WebVRController));
  60440. BABYLON.ViveController = ViveController;
  60441. })(BABYLON || (BABYLON = {}));
  60442. //# sourceMappingURL=babylon.viveController.js.map
  60443. var BABYLON;
  60444. (function (BABYLON) {
  60445. var GenericController = /** @class */ (function (_super) {
  60446. __extends(GenericController, _super);
  60447. function GenericController(vrGamepad) {
  60448. return _super.call(this, vrGamepad) || this;
  60449. }
  60450. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60451. var _this = this;
  60452. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  60453. _this._defaultModel = newMeshes[1];
  60454. _this.attachToMesh(_this._defaultModel);
  60455. if (meshLoaded) {
  60456. meshLoaded(_this._defaultModel);
  60457. }
  60458. });
  60459. };
  60460. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60461. console.log("Button id: " + buttonIdx + "state: ");
  60462. console.dir(state);
  60463. };
  60464. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60465. GenericController.MODEL_FILENAME = 'generic.babylon';
  60466. return GenericController;
  60467. }(BABYLON.WebVRController));
  60468. BABYLON.GenericController = GenericController;
  60469. })(BABYLON || (BABYLON = {}));
  60470. //# sourceMappingURL=babylon.genericController.js.map
  60471. var BABYLON;
  60472. (function (BABYLON) {
  60473. var LoadedMeshInfo = /** @class */ (function () {
  60474. function LoadedMeshInfo() {
  60475. this.buttonMeshes = {};
  60476. this.axisMeshes = {};
  60477. }
  60478. return LoadedMeshInfo;
  60479. }());
  60480. var WindowsMotionController = /** @class */ (function (_super) {
  60481. __extends(WindowsMotionController, _super);
  60482. function WindowsMotionController(vrGamepad) {
  60483. var _this = _super.call(this, vrGamepad) || this;
  60484. _this._mapping = {
  60485. // Semantic button names
  60486. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  60487. // A mapping of the button name to glTF model node name
  60488. // that should be transformed by button value.
  60489. buttonMeshNames: {
  60490. 'trigger': 'SELECT',
  60491. 'menu': 'MENU',
  60492. 'grip': 'GRASP',
  60493. 'thumbstick': 'THUMBSTICK_PRESS',
  60494. 'trackpad': 'TOUCHPAD_PRESS'
  60495. },
  60496. // This mapping is used to translate from the Motion Controller to Babylon semantics
  60497. buttonObservableNames: {
  60498. 'trigger': 'onTriggerStateChangedObservable',
  60499. 'menu': 'onSecondaryButtonStateChangedObservable',
  60500. 'grip': 'onMainButtonStateChangedObservable',
  60501. 'thumbstick': 'onPadStateChangedObservable',
  60502. 'trackpad': 'onTrackpadChangedObservable'
  60503. },
  60504. // A mapping of the axis name to glTF model node name
  60505. // that should be transformed by axis value.
  60506. // This array mirrors the browserGamepad.axes array, such that
  60507. // the mesh corresponding to axis 0 is in this array index 0.
  60508. axisMeshNames: [
  60509. 'THUMBSTICK_X',
  60510. 'THUMBSTICK_Y',
  60511. 'TOUCHPAD_TOUCH_X',
  60512. 'TOUCHPAD_TOUCH_Y'
  60513. ],
  60514. pointingPoseMeshName: 'POINTING_POSE'
  60515. };
  60516. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  60517. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  60518. _this.trackpad = { x: 0, y: 0 };
  60519. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  60520. _this._loadedMeshInfo = null;
  60521. return _this;
  60522. }
  60523. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  60524. get: function () {
  60525. return this.onTriggerStateChangedObservable;
  60526. },
  60527. enumerable: true,
  60528. configurable: true
  60529. });
  60530. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  60531. get: function () {
  60532. return this.onSecondaryButtonStateChangedObservable;
  60533. },
  60534. enumerable: true,
  60535. configurable: true
  60536. });
  60537. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  60538. get: function () {
  60539. return this.onMainButtonStateChangedObservable;
  60540. },
  60541. enumerable: true,
  60542. configurable: true
  60543. });
  60544. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  60545. get: function () {
  60546. return this.onPadStateChangedObservable;
  60547. },
  60548. enumerable: true,
  60549. configurable: true
  60550. });
  60551. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  60552. get: function () {
  60553. return this.onTrackpadChangedObservable;
  60554. },
  60555. enumerable: true,
  60556. configurable: true
  60557. });
  60558. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  60559. get: function () {
  60560. return this.onTrackpadValuesChangedObservable;
  60561. },
  60562. enumerable: true,
  60563. configurable: true
  60564. });
  60565. /**
  60566. * Called once per frame by the engine.
  60567. */
  60568. WindowsMotionController.prototype.update = function () {
  60569. _super.prototype.update.call(this);
  60570. // Only need to animate axes if there is a loaded mesh
  60571. if (this._loadedMeshInfo) {
  60572. if (this.browserGamepad.axes) {
  60573. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  60574. this.trackpad.x = this.browserGamepad["axes"][2];
  60575. this.trackpad.y = this.browserGamepad["axes"][3];
  60576. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  60577. }
  60578. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  60579. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  60580. }
  60581. }
  60582. }
  60583. };
  60584. /**
  60585. * Called once for each button that changed state since the last frame
  60586. * @param buttonIdx Which button index changed
  60587. * @param state New state of the button
  60588. * @param changes Which properties on the state changed since last frame
  60589. */
  60590. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60591. var buttonName = this._mapping.buttons[buttonIdx];
  60592. if (!buttonName) {
  60593. return;
  60594. }
  60595. // Only emit events for buttons that we know how to map from index to name
  60596. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  60597. if (observable) {
  60598. observable.notifyObservers(state);
  60599. }
  60600. this.lerpButtonTransform(buttonName, state.value);
  60601. };
  60602. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  60603. // If there is no loaded mesh, there is nothing to transform.
  60604. if (!this._loadedMeshInfo) {
  60605. return;
  60606. }
  60607. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  60608. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60609. return;
  60610. }
  60611. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  60612. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  60613. };
  60614. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  60615. if (!this._loadedMeshInfo) {
  60616. return;
  60617. }
  60618. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  60619. if (!meshInfo) {
  60620. return;
  60621. }
  60622. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60623. return;
  60624. }
  60625. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  60626. var lerpValue = axisValue * 0.5 + 0.5;
  60627. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  60628. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  60629. };
  60630. /**
  60631. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  60632. * @param scene scene in which to add meshes
  60633. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  60634. */
  60635. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  60636. var _this = this;
  60637. if (forceDefault === void 0) { forceDefault = false; }
  60638. var path;
  60639. var filename;
  60640. // Checking if GLB loader is present
  60641. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  60642. // Determine the device specific folder based on the ID suffix
  60643. var device = 'default';
  60644. if (this.id && !forceDefault) {
  60645. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  60646. device = ((match && match[0]) || device);
  60647. }
  60648. // Hand
  60649. if (this.hand === 'left') {
  60650. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  60651. }
  60652. else {
  60653. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  60654. }
  60655. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  60656. }
  60657. else {
  60658. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  60659. path = BABYLON.GenericController.MODEL_BASE_URL;
  60660. filename = BABYLON.GenericController.MODEL_FILENAME;
  60661. }
  60662. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  60663. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  60664. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  60665. if (!_this._loadedMeshInfo) {
  60666. return;
  60667. }
  60668. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  60669. _this.attachToMesh(_this._defaultModel);
  60670. if (meshLoaded) {
  60671. meshLoaded(_this._defaultModel);
  60672. }
  60673. }, null, function (scene, message) {
  60674. BABYLON.Tools.Log(message);
  60675. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  60676. if (!forceDefault) {
  60677. _this.initControllerMesh(scene, meshLoaded, true);
  60678. }
  60679. });
  60680. };
  60681. /**
  60682. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  60683. * can be transformed by button presses and axes values, based on this._mapping.
  60684. *
  60685. * @param scene scene in which the meshes exist
  60686. * @param meshes list of meshes that make up the controller model to process
  60687. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  60688. */
  60689. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  60690. var loadedMeshInfo = null;
  60691. // Create a new mesh to contain the glTF hierarchy
  60692. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  60693. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  60694. var childMesh = null;
  60695. for (var i = 0; i < meshes.length; i++) {
  60696. var mesh = meshes[i];
  60697. if (!mesh.parent) {
  60698. // Exclude controller meshes from picking results
  60699. mesh.isPickable = false;
  60700. // Handle root node, attach to the new parentMesh
  60701. childMesh = mesh;
  60702. break;
  60703. }
  60704. }
  60705. if (childMesh) {
  60706. childMesh.setParent(parentMesh);
  60707. // Create our mesh info. Note that this method will always return non-null.
  60708. loadedMeshInfo = this.createMeshInfo(parentMesh);
  60709. }
  60710. else {
  60711. BABYLON.Tools.Warn('Could not find root node in model file.');
  60712. }
  60713. return loadedMeshInfo;
  60714. };
  60715. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  60716. var loadedMeshInfo = new LoadedMeshInfo();
  60717. var i;
  60718. loadedMeshInfo.rootNode = rootNode;
  60719. // Reset the caches
  60720. loadedMeshInfo.buttonMeshes = {};
  60721. loadedMeshInfo.axisMeshes = {};
  60722. // Button Meshes
  60723. for (i = 0; i < this._mapping.buttons.length; i++) {
  60724. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  60725. if (!buttonMeshName) {
  60726. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  60727. continue;
  60728. }
  60729. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  60730. if (!buttonMesh) {
  60731. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  60732. continue;
  60733. }
  60734. var buttonMeshInfo = {
  60735. index: i,
  60736. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  60737. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  60738. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  60739. };
  60740. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  60741. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  60742. }
  60743. else {
  60744. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  60745. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  60746. '(VALUE: ' + !!buttonMeshInfo.value +
  60747. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  60748. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  60749. ')');
  60750. }
  60751. }
  60752. // Axis Meshes
  60753. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  60754. var axisMeshName = this._mapping.axisMeshNames[i];
  60755. if (!axisMeshName) {
  60756. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  60757. continue;
  60758. }
  60759. var axisMesh = getChildByName(rootNode, axisMeshName);
  60760. if (!axisMesh) {
  60761. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  60762. continue;
  60763. }
  60764. var axisMeshInfo = {
  60765. index: i,
  60766. value: getImmediateChildByName(axisMesh, 'VALUE'),
  60767. min: getImmediateChildByName(axisMesh, 'MIN'),
  60768. max: getImmediateChildByName(axisMesh, 'MAX')
  60769. };
  60770. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  60771. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  60772. }
  60773. else {
  60774. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  60775. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  60776. '(VALUE: ' + !!axisMeshInfo.value +
  60777. ', MIN: ' + !!axisMeshInfo.min +
  60778. ', MAX:' + !!axisMeshInfo.max +
  60779. ')');
  60780. }
  60781. }
  60782. // Pointing Ray
  60783. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  60784. if (!loadedMeshInfo.pointingPoseNode) {
  60785. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  60786. }
  60787. return loadedMeshInfo;
  60788. // Look through all children recursively. This will return null if no mesh exists with the given name.
  60789. function getChildByName(node, name) {
  60790. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  60791. }
  60792. // Look through only immediate children. This will return null if no mesh exists with the given name.
  60793. function getImmediateChildByName(node, name) {
  60794. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  60795. }
  60796. };
  60797. WindowsMotionController.prototype.getForwardRay = function (length) {
  60798. if (length === void 0) { length = 100; }
  60799. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  60800. return _super.prototype.getForwardRay.call(this, length);
  60801. }
  60802. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  60803. var origin = m.getTranslation();
  60804. var forward = new BABYLON.Vector3(0, 0, -1);
  60805. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60806. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60807. return new BABYLON.Ray(origin, direction, length);
  60808. };
  60809. WindowsMotionController.prototype.dispose = function () {
  60810. _super.prototype.dispose.call(this);
  60811. this.onTrackpadChangedObservable.clear();
  60812. };
  60813. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  60814. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  60815. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  60816. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  60817. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  60818. return WindowsMotionController;
  60819. }(BABYLON.WebVRController));
  60820. BABYLON.WindowsMotionController = WindowsMotionController;
  60821. })(BABYLON || (BABYLON = {}));
  60822. //# sourceMappingURL=babylon.windowsMotionController.js.map
  60823. var BABYLON;
  60824. (function (BABYLON) {
  60825. var GearVRController = /** @class */ (function (_super) {
  60826. __extends(GearVRController, _super);
  60827. function GearVRController(vrGamepad) {
  60828. var _this = _super.call(this, vrGamepad) || this;
  60829. _this._buttonIndexToObservableNameMap = [
  60830. 'onTrackpadChangedObservable',
  60831. 'onTriggerStateChangedObservable' // Trigger
  60832. ];
  60833. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  60834. return _this;
  60835. }
  60836. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60837. var _this = this;
  60838. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  60839. _this._defaultModel = newMeshes[1];
  60840. _this.attachToMesh(_this._defaultModel);
  60841. if (meshLoaded) {
  60842. meshLoaded(_this._defaultModel);
  60843. }
  60844. });
  60845. };
  60846. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60847. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  60848. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  60849. // Only emit events for buttons that we know how to map from index to observable
  60850. var observable = this[observableName];
  60851. if (observable) {
  60852. observable.notifyObservers(state);
  60853. }
  60854. }
  60855. };
  60856. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60857. GearVRController.MODEL_FILENAME = 'generic.babylon';
  60858. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  60859. return GearVRController;
  60860. }(BABYLON.WebVRController));
  60861. BABYLON.GearVRController = GearVRController;
  60862. })(BABYLON || (BABYLON = {}));
  60863. //# sourceMappingURL=babylon.gearVRController.js.map
  60864. var BABYLON;
  60865. (function (BABYLON) {
  60866. var FollowCamera = /** @class */ (function (_super) {
  60867. __extends(FollowCamera, _super);
  60868. function FollowCamera(name, position, scene, lockedTarget) {
  60869. if (lockedTarget === void 0) { lockedTarget = null; }
  60870. var _this = _super.call(this, name, position, scene) || this;
  60871. _this.radius = 12;
  60872. _this.rotationOffset = 0;
  60873. _this.heightOffset = 4;
  60874. _this.cameraAcceleration = 0.05;
  60875. _this.maxCameraSpeed = 20;
  60876. _this.lockedTarget = lockedTarget;
  60877. return _this;
  60878. }
  60879. FollowCamera.prototype.getRadians = function (degrees) {
  60880. return degrees * Math.PI / 180;
  60881. };
  60882. FollowCamera.prototype.follow = function (cameraTarget) {
  60883. if (!cameraTarget)
  60884. return;
  60885. var yRotation;
  60886. if (cameraTarget.rotationQuaternion) {
  60887. var rotMatrix = new BABYLON.Matrix();
  60888. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  60889. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  60890. }
  60891. else {
  60892. yRotation = cameraTarget.rotation.y;
  60893. }
  60894. var radians = this.getRadians(this.rotationOffset) + yRotation;
  60895. var targetPosition = cameraTarget.getAbsolutePosition();
  60896. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  60897. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  60898. var dx = targetX - this.position.x;
  60899. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  60900. var dz = (targetZ) - this.position.z;
  60901. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  60902. var vy = dy * this.cameraAcceleration;
  60903. var vz = dz * this.cameraAcceleration * 2;
  60904. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  60905. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60906. }
  60907. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  60908. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60909. }
  60910. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  60911. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60912. }
  60913. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  60914. this.setTarget(targetPosition);
  60915. };
  60916. FollowCamera.prototype._checkInputs = function () {
  60917. _super.prototype._checkInputs.call(this);
  60918. if (this.lockedTarget) {
  60919. this.follow(this.lockedTarget);
  60920. }
  60921. };
  60922. FollowCamera.prototype.getClassName = function () {
  60923. return "FollowCamera";
  60924. };
  60925. __decorate([
  60926. BABYLON.serialize()
  60927. ], FollowCamera.prototype, "radius", void 0);
  60928. __decorate([
  60929. BABYLON.serialize()
  60930. ], FollowCamera.prototype, "rotationOffset", void 0);
  60931. __decorate([
  60932. BABYLON.serialize()
  60933. ], FollowCamera.prototype, "heightOffset", void 0);
  60934. __decorate([
  60935. BABYLON.serialize()
  60936. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  60937. __decorate([
  60938. BABYLON.serialize()
  60939. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  60940. __decorate([
  60941. BABYLON.serializeAsMeshReference("lockedTargetId")
  60942. ], FollowCamera.prototype, "lockedTarget", void 0);
  60943. return FollowCamera;
  60944. }(BABYLON.TargetCamera));
  60945. BABYLON.FollowCamera = FollowCamera;
  60946. var ArcFollowCamera = /** @class */ (function (_super) {
  60947. __extends(ArcFollowCamera, _super);
  60948. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  60949. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  60950. _this.alpha = alpha;
  60951. _this.beta = beta;
  60952. _this.radius = radius;
  60953. _this.target = target;
  60954. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  60955. _this.follow();
  60956. return _this;
  60957. }
  60958. ArcFollowCamera.prototype.follow = function () {
  60959. if (!this.target) {
  60960. return;
  60961. }
  60962. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  60963. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  60964. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  60965. var targetPosition = this.target.getAbsolutePosition();
  60966. this.position = targetPosition.add(this._cartesianCoordinates);
  60967. this.setTarget(targetPosition);
  60968. };
  60969. ArcFollowCamera.prototype._checkInputs = function () {
  60970. _super.prototype._checkInputs.call(this);
  60971. this.follow();
  60972. };
  60973. ArcFollowCamera.prototype.getClassName = function () {
  60974. return "ArcFollowCamera";
  60975. };
  60976. return ArcFollowCamera;
  60977. }(BABYLON.TargetCamera));
  60978. BABYLON.ArcFollowCamera = ArcFollowCamera;
  60979. })(BABYLON || (BABYLON = {}));
  60980. //# sourceMappingURL=babylon.followCamera.js.map
  60981. var BABYLON;
  60982. (function (BABYLON) {
  60983. // We're mainly based on the logic defined into the FreeCamera code
  60984. var UniversalCamera = /** @class */ (function (_super) {
  60985. __extends(UniversalCamera, _super);
  60986. //-- end properties for backward compatibility for inputs
  60987. function UniversalCamera(name, position, scene) {
  60988. var _this = _super.call(this, name, position, scene) || this;
  60989. _this.inputs.addGamepad();
  60990. return _this;
  60991. }
  60992. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  60993. //-- Begin properties for backward compatibility for inputs
  60994. get: function () {
  60995. var gamepad = this.inputs.attached["gamepad"];
  60996. if (gamepad)
  60997. return gamepad.gamepadAngularSensibility;
  60998. return 0;
  60999. },
  61000. set: function (value) {
  61001. var gamepad = this.inputs.attached["gamepad"];
  61002. if (gamepad)
  61003. gamepad.gamepadAngularSensibility = value;
  61004. },
  61005. enumerable: true,
  61006. configurable: true
  61007. });
  61008. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  61009. get: function () {
  61010. var gamepad = this.inputs.attached["gamepad"];
  61011. if (gamepad)
  61012. return gamepad.gamepadMoveSensibility;
  61013. return 0;
  61014. },
  61015. set: function (value) {
  61016. var gamepad = this.inputs.attached["gamepad"];
  61017. if (gamepad)
  61018. gamepad.gamepadMoveSensibility = value;
  61019. },
  61020. enumerable: true,
  61021. configurable: true
  61022. });
  61023. UniversalCamera.prototype.getClassName = function () {
  61024. return "UniversalCamera";
  61025. };
  61026. return UniversalCamera;
  61027. }(BABYLON.TouchCamera));
  61028. BABYLON.UniversalCamera = UniversalCamera;
  61029. })(BABYLON || (BABYLON = {}));
  61030. //# sourceMappingURL=babylon.universalCamera.js.map
  61031. var BABYLON;
  61032. (function (BABYLON) {
  61033. // We're mainly based on the logic defined into the FreeCamera code
  61034. var GamepadCamera = /** @class */ (function (_super) {
  61035. __extends(GamepadCamera, _super);
  61036. //-- end properties for backward compatibility for inputs
  61037. function GamepadCamera(name, position, scene) {
  61038. return _super.call(this, name, position, scene) || this;
  61039. }
  61040. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  61041. //-- Begin properties for backward compatibility for inputs
  61042. get: function () {
  61043. var gamepad = this.inputs.attached["gamepad"];
  61044. if (gamepad)
  61045. return gamepad.gamepadAngularSensibility;
  61046. return 0;
  61047. },
  61048. set: function (value) {
  61049. var gamepad = this.inputs.attached["gamepad"];
  61050. if (gamepad)
  61051. gamepad.gamepadAngularSensibility = value;
  61052. },
  61053. enumerable: true,
  61054. configurable: true
  61055. });
  61056. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  61057. get: function () {
  61058. var gamepad = this.inputs.attached["gamepad"];
  61059. if (gamepad)
  61060. return gamepad.gamepadMoveSensibility;
  61061. return 0;
  61062. },
  61063. set: function (value) {
  61064. var gamepad = this.inputs.attached["gamepad"];
  61065. if (gamepad)
  61066. gamepad.gamepadMoveSensibility = value;
  61067. },
  61068. enumerable: true,
  61069. configurable: true
  61070. });
  61071. GamepadCamera.prototype.getClassName = function () {
  61072. return "GamepadCamera";
  61073. };
  61074. return GamepadCamera;
  61075. }(BABYLON.UniversalCamera));
  61076. BABYLON.GamepadCamera = GamepadCamera;
  61077. })(BABYLON || (BABYLON = {}));
  61078. //# sourceMappingURL=babylon.gamepadCamera.js.map
  61079. var BABYLON;
  61080. (function (BABYLON) {
  61081. var PostProcessRenderPipelineManager = /** @class */ (function () {
  61082. function PostProcessRenderPipelineManager() {
  61083. this._renderPipelines = {};
  61084. }
  61085. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  61086. this._renderPipelines[renderPipeline._name] = renderPipeline;
  61087. };
  61088. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  61089. if (unique === void 0) { unique = false; }
  61090. var renderPipeline = this._renderPipelines[renderPipelineName];
  61091. if (!renderPipeline) {
  61092. return;
  61093. }
  61094. renderPipeline._attachCameras(cameras, unique);
  61095. };
  61096. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  61097. var renderPipeline = this._renderPipelines[renderPipelineName];
  61098. if (!renderPipeline) {
  61099. return;
  61100. }
  61101. renderPipeline._detachCameras(cameras);
  61102. };
  61103. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61104. var renderPipeline = this._renderPipelines[renderPipelineName];
  61105. if (!renderPipeline) {
  61106. return;
  61107. }
  61108. renderPipeline._enableEffect(renderEffectName, cameras);
  61109. };
  61110. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61111. var renderPipeline = this._renderPipelines[renderPipelineName];
  61112. if (!renderPipeline) {
  61113. return;
  61114. }
  61115. renderPipeline._disableEffect(renderEffectName, cameras);
  61116. };
  61117. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  61118. var renderPipeline = this._renderPipelines[renderPipelineName];
  61119. if (!renderPipeline) {
  61120. return;
  61121. }
  61122. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  61123. };
  61124. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  61125. var renderPipeline = this._renderPipelines[renderPipelineName];
  61126. if (!renderPipeline) {
  61127. return;
  61128. }
  61129. renderPipeline._disableDisplayOnlyPass(cameras);
  61130. };
  61131. PostProcessRenderPipelineManager.prototype.update = function () {
  61132. for (var renderPipelineName in this._renderPipelines) {
  61133. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61134. var pipeline = this._renderPipelines[renderPipelineName];
  61135. if (!pipeline.isSupported) {
  61136. pipeline.dispose();
  61137. delete this._renderPipelines[renderPipelineName];
  61138. }
  61139. else {
  61140. pipeline._update();
  61141. }
  61142. }
  61143. }
  61144. };
  61145. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  61146. for (var renderPipelineName in this._renderPipelines) {
  61147. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61148. var pipeline = this._renderPipelines[renderPipelineName];
  61149. pipeline._rebuild();
  61150. }
  61151. }
  61152. };
  61153. PostProcessRenderPipelineManager.prototype.dispose = function () {
  61154. for (var renderPipelineName in this._renderPipelines) {
  61155. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61156. var pipeline = this._renderPipelines[renderPipelineName];
  61157. pipeline.dispose();
  61158. }
  61159. }
  61160. };
  61161. return PostProcessRenderPipelineManager;
  61162. }());
  61163. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  61164. })(BABYLON || (BABYLON = {}));
  61165. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  61166. var BABYLON;
  61167. (function (BABYLON) {
  61168. var PostProcessRenderPass = /** @class */ (function () {
  61169. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  61170. this._refCount = 0;
  61171. this._name = name;
  61172. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  61173. this.setRenderList(renderList);
  61174. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  61175. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61176. this._scene = scene;
  61177. this._renderList = renderList;
  61178. }
  61179. // private
  61180. PostProcessRenderPass.prototype._incRefCount = function () {
  61181. if (this._refCount === 0) {
  61182. this._scene.customRenderTargets.push(this._renderTexture);
  61183. }
  61184. return ++this._refCount;
  61185. };
  61186. PostProcessRenderPass.prototype._decRefCount = function () {
  61187. this._refCount--;
  61188. if (this._refCount <= 0) {
  61189. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61190. }
  61191. return this._refCount;
  61192. };
  61193. PostProcessRenderPass.prototype._update = function () {
  61194. this.setRenderList(this._renderList);
  61195. };
  61196. // public
  61197. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61198. this._renderTexture.renderList = renderList;
  61199. };
  61200. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61201. return this._renderTexture;
  61202. };
  61203. return PostProcessRenderPass;
  61204. }());
  61205. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61206. })(BABYLON || (BABYLON = {}));
  61207. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61208. var BABYLON;
  61209. (function (BABYLON) {
  61210. var PostProcessRenderEffect = /** @class */ (function () {
  61211. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61212. this._name = name;
  61213. this._singleInstance = singleInstance || true;
  61214. this._getPostProcess = getPostProcess;
  61215. this._cameras = {};
  61216. this._indicesForCamera = {};
  61217. this._postProcesses = {};
  61218. this._renderPasses = {};
  61219. this._renderEffectAsPasses = {};
  61220. }
  61221. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61222. get: function () {
  61223. for (var index in this._postProcesses) {
  61224. if (!this._postProcesses[index].isSupported) {
  61225. return false;
  61226. }
  61227. }
  61228. return true;
  61229. },
  61230. enumerable: true,
  61231. configurable: true
  61232. });
  61233. PostProcessRenderEffect.prototype._update = function () {
  61234. for (var renderPassName in this._renderPasses) {
  61235. this._renderPasses[renderPassName]._update();
  61236. }
  61237. };
  61238. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61239. this._renderPasses[renderPass._name] = renderPass;
  61240. this._linkParameters();
  61241. };
  61242. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61243. delete this._renderPasses[renderPass._name];
  61244. this._linkParameters();
  61245. };
  61246. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61247. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61248. this._linkParameters();
  61249. };
  61250. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61251. for (var renderPassName in this._renderPasses) {
  61252. if (renderPassName === passName) {
  61253. return this._renderPasses[passName];
  61254. }
  61255. }
  61256. return null;
  61257. };
  61258. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61259. this._renderPasses = {};
  61260. this._linkParameters();
  61261. };
  61262. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61263. var cameraKey;
  61264. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61265. if (!cams) {
  61266. return;
  61267. }
  61268. for (var i = 0; i < cams.length; i++) {
  61269. var camera = cams[i];
  61270. var cameraName = camera.name;
  61271. if (this._singleInstance) {
  61272. cameraKey = 0;
  61273. }
  61274. else {
  61275. cameraKey = cameraName;
  61276. }
  61277. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61278. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61279. if (!this._indicesForCamera[cameraName]) {
  61280. this._indicesForCamera[cameraName] = [];
  61281. }
  61282. this._indicesForCamera[cameraName].push(index);
  61283. if (!this._cameras[cameraName]) {
  61284. this._cameras[cameraName] = camera;
  61285. }
  61286. for (var passName in this._renderPasses) {
  61287. this._renderPasses[passName]._incRefCount();
  61288. }
  61289. }
  61290. this._linkParameters();
  61291. };
  61292. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61293. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61294. if (!cams) {
  61295. return;
  61296. }
  61297. for (var i = 0; i < cams.length; i++) {
  61298. var camera = cams[i];
  61299. var cameraName = camera.name;
  61300. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61301. if (this._cameras[cameraName]) {
  61302. //this._indicesForCamera.splice(index, 1);
  61303. this._cameras[cameraName] = null;
  61304. }
  61305. for (var passName in this._renderPasses) {
  61306. this._renderPasses[passName]._decRefCount();
  61307. }
  61308. }
  61309. };
  61310. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61311. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61312. if (!cams) {
  61313. return;
  61314. }
  61315. for (var i = 0; i < cams.length; i++) {
  61316. var camera = cams[i];
  61317. var cameraName = camera.name;
  61318. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61319. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61320. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61321. }
  61322. }
  61323. for (var passName in this._renderPasses) {
  61324. this._renderPasses[passName]._incRefCount();
  61325. }
  61326. }
  61327. };
  61328. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61329. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61330. if (!cams) {
  61331. return;
  61332. }
  61333. for (var i = 0; i < cams.length; i++) {
  61334. var camera = cams[i];
  61335. var cameraName = camera.Name;
  61336. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61337. for (var passName in this._renderPasses) {
  61338. this._renderPasses[passName]._decRefCount();
  61339. }
  61340. }
  61341. };
  61342. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61343. if (this._singleInstance) {
  61344. return this._postProcesses[0];
  61345. }
  61346. else {
  61347. if (!camera) {
  61348. return null;
  61349. }
  61350. return this._postProcesses[camera.name];
  61351. }
  61352. };
  61353. PostProcessRenderEffect.prototype._linkParameters = function () {
  61354. var _this = this;
  61355. for (var index in this._postProcesses) {
  61356. if (this.applyParameters) {
  61357. this.applyParameters(this._postProcesses[index]);
  61358. }
  61359. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61360. _this._linkTextures(effect);
  61361. });
  61362. }
  61363. };
  61364. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61365. for (var renderPassName in this._renderPasses) {
  61366. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61367. }
  61368. for (var renderEffectName in this._renderEffectAsPasses) {
  61369. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61370. }
  61371. };
  61372. return PostProcessRenderEffect;
  61373. }());
  61374. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61375. })(BABYLON || (BABYLON = {}));
  61376. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61377. var BABYLON;
  61378. (function (BABYLON) {
  61379. var PostProcessRenderPipeline = /** @class */ (function () {
  61380. function PostProcessRenderPipeline(engine, name) {
  61381. this._engine = engine;
  61382. this._name = name;
  61383. this._renderEffects = {};
  61384. this._renderEffectsForIsolatedPass = new Array();
  61385. this._cameras = [];
  61386. }
  61387. PostProcessRenderPipeline.prototype.getClassName = function () {
  61388. return "PostProcessRenderPipeline";
  61389. };
  61390. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61391. get: function () {
  61392. for (var renderEffectName in this._renderEffects) {
  61393. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61394. if (!this._renderEffects[renderEffectName].isSupported) {
  61395. return false;
  61396. }
  61397. }
  61398. }
  61399. return true;
  61400. },
  61401. enumerable: true,
  61402. configurable: true
  61403. });
  61404. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61405. this._renderEffects[renderEffect._name] = renderEffect;
  61406. };
  61407. // private
  61408. PostProcessRenderPipeline.prototype._rebuild = function () {
  61409. };
  61410. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  61411. var renderEffects = this._renderEffects[renderEffectName];
  61412. if (!renderEffects) {
  61413. return;
  61414. }
  61415. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61416. };
  61417. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  61418. var renderEffects = this._renderEffects[renderEffectName];
  61419. if (!renderEffects) {
  61420. return;
  61421. }
  61422. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61423. };
  61424. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  61425. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61426. if (!cams) {
  61427. return;
  61428. }
  61429. var indicesToDelete = [];
  61430. var i;
  61431. for (i = 0; i < cams.length; i++) {
  61432. var camera = cams[i];
  61433. var cameraName = camera.name;
  61434. if (this._cameras.indexOf(camera) === -1) {
  61435. this._cameras[cameraName] = camera;
  61436. }
  61437. else if (unique) {
  61438. indicesToDelete.push(i);
  61439. }
  61440. }
  61441. for (i = 0; i < indicesToDelete.length; i++) {
  61442. cameras.splice(indicesToDelete[i], 1);
  61443. }
  61444. for (var renderEffectName in this._renderEffects) {
  61445. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61446. this._renderEffects[renderEffectName]._attachCameras(cams);
  61447. }
  61448. }
  61449. };
  61450. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  61451. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61452. if (!cams) {
  61453. return;
  61454. }
  61455. for (var renderEffectName in this._renderEffects) {
  61456. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61457. this._renderEffects[renderEffectName]._detachCameras(cams);
  61458. }
  61459. }
  61460. for (var i = 0; i < cams.length; i++) {
  61461. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  61462. }
  61463. };
  61464. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  61465. var _this = this;
  61466. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61467. if (!cams) {
  61468. return;
  61469. }
  61470. var pass = null;
  61471. var renderEffectName;
  61472. for (renderEffectName in this._renderEffects) {
  61473. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61474. pass = this._renderEffects[renderEffectName].getPass(passName);
  61475. if (pass != null) {
  61476. break;
  61477. }
  61478. }
  61479. }
  61480. if (pass === null) {
  61481. return;
  61482. }
  61483. for (renderEffectName in this._renderEffects) {
  61484. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61485. this._renderEffects[renderEffectName]._disable(cams);
  61486. }
  61487. }
  61488. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  61489. for (var i = 0; i < cams.length; i++) {
  61490. var camera = cams[i];
  61491. var cameraName = camera.name;
  61492. 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); });
  61493. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  61494. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  61495. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  61496. }
  61497. };
  61498. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  61499. var _this = this;
  61500. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61501. if (!cams) {
  61502. return;
  61503. }
  61504. for (var i = 0; i < cams.length; i++) {
  61505. var camera = cams[i];
  61506. var cameraName = camera.name;
  61507. 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); });
  61508. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  61509. }
  61510. for (var renderEffectName in this._renderEffects) {
  61511. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61512. this._renderEffects[renderEffectName]._enable(cams);
  61513. }
  61514. }
  61515. };
  61516. PostProcessRenderPipeline.prototype._update = function () {
  61517. for (var renderEffectName in this._renderEffects) {
  61518. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61519. this._renderEffects[renderEffectName]._update();
  61520. }
  61521. }
  61522. for (var i = 0; i < this._cameras.length; i++) {
  61523. var cameraName = this._cameras[i].name;
  61524. if (this._renderEffectsForIsolatedPass[cameraName]) {
  61525. this._renderEffectsForIsolatedPass[cameraName]._update();
  61526. }
  61527. }
  61528. };
  61529. PostProcessRenderPipeline.prototype._reset = function () {
  61530. this._renderEffects = {};
  61531. this._renderEffectsForIsolatedPass = new Array();
  61532. };
  61533. PostProcessRenderPipeline.prototype.dispose = function () {
  61534. // Must be implemented by children
  61535. };
  61536. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  61537. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  61538. __decorate([
  61539. BABYLON.serialize()
  61540. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  61541. return PostProcessRenderPipeline;
  61542. }());
  61543. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  61544. })(BABYLON || (BABYLON = {}));
  61545. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  61546. var BABYLON;
  61547. (function (BABYLON) {
  61548. var DepthRenderer = /** @class */ (function () {
  61549. function DepthRenderer(scene, type) {
  61550. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  61551. var _this = this;
  61552. this._scene = scene;
  61553. var engine = scene.getEngine();
  61554. // Render target
  61555. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  61556. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61557. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61558. this._depthMap.refreshRate = 1;
  61559. this._depthMap.renderParticles = false;
  61560. this._depthMap.renderList = null;
  61561. // set default depth value to 1.0 (far away)
  61562. this._depthMap.onClearObservable.add(function (engine) {
  61563. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  61564. });
  61565. // Custom render function
  61566. var renderSubMesh = function (subMesh) {
  61567. var mesh = subMesh.getRenderingMesh();
  61568. var scene = _this._scene;
  61569. var engine = scene.getEngine();
  61570. var material = subMesh.getMaterial();
  61571. if (!material) {
  61572. return;
  61573. }
  61574. // Culling and reverse (right handed system)
  61575. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61576. // Managing instances
  61577. var batch = mesh._getInstancesRenderList(subMesh._id);
  61578. if (batch.mustReturn) {
  61579. return;
  61580. }
  61581. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61582. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  61583. engine.enableEffect(_this._effect);
  61584. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61585. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61586. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  61587. // Alpha test
  61588. if (material && material.needAlphaTesting()) {
  61589. var alphaTexture = material.getAlphaTestTexture();
  61590. if (alphaTexture) {
  61591. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61592. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61593. }
  61594. }
  61595. // Bones
  61596. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61597. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61598. }
  61599. // Draw
  61600. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61601. }
  61602. };
  61603. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61604. var index;
  61605. if (depthOnlySubMeshes.length) {
  61606. engine.setColorWrite(false);
  61607. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61608. renderSubMesh(depthOnlySubMeshes.data[index]);
  61609. }
  61610. engine.setColorWrite(true);
  61611. }
  61612. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61613. renderSubMesh(opaqueSubMeshes.data[index]);
  61614. }
  61615. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61616. renderSubMesh(alphaTestSubMeshes.data[index]);
  61617. }
  61618. };
  61619. }
  61620. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  61621. var material = subMesh.getMaterial();
  61622. if (material.disableDepthWrite) {
  61623. return false;
  61624. }
  61625. var defines = [];
  61626. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61627. var mesh = subMesh.getMesh();
  61628. // Alpha test
  61629. if (material && material.needAlphaTesting()) {
  61630. defines.push("#define ALPHATEST");
  61631. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61632. attribs.push(BABYLON.VertexBuffer.UVKind);
  61633. defines.push("#define UV1");
  61634. }
  61635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61636. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61637. defines.push("#define UV2");
  61638. }
  61639. }
  61640. // Bones
  61641. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61642. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61643. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61644. if (mesh.numBoneInfluencers > 4) {
  61645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61647. }
  61648. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61649. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61650. }
  61651. else {
  61652. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61653. }
  61654. // Instances
  61655. if (useInstances) {
  61656. defines.push("#define INSTANCES");
  61657. attribs.push("world0");
  61658. attribs.push("world1");
  61659. attribs.push("world2");
  61660. attribs.push("world3");
  61661. }
  61662. // Get correct effect
  61663. var join = defines.join("\n");
  61664. if (this._cachedDefines !== join) {
  61665. this._cachedDefines = join;
  61666. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  61667. }
  61668. return this._effect.isReady();
  61669. };
  61670. DepthRenderer.prototype.getDepthMap = function () {
  61671. return this._depthMap;
  61672. };
  61673. // Methods
  61674. DepthRenderer.prototype.dispose = function () {
  61675. this._depthMap.dispose();
  61676. };
  61677. return DepthRenderer;
  61678. }());
  61679. BABYLON.DepthRenderer = DepthRenderer;
  61680. })(BABYLON || (BABYLON = {}));
  61681. //# sourceMappingURL=babylon.depthRenderer.js.map
  61682. var BABYLON;
  61683. (function (BABYLON) {
  61684. var SSAORenderingPipeline = /** @class */ (function (_super) {
  61685. __extends(SSAORenderingPipeline, _super);
  61686. /**
  61687. * @constructor
  61688. * @param {string} name - The rendering pipeline name
  61689. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61690. * @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 }
  61691. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61692. */
  61693. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  61694. var _this = _super.call(this, scene.getEngine(), name) || this;
  61695. // Members
  61696. /**
  61697. * The PassPostProcess id in the pipeline that contains the original scene color
  61698. * @type {string}
  61699. */
  61700. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61701. /**
  61702. * The SSAO PostProcess id in the pipeline
  61703. * @type {string}
  61704. */
  61705. _this.SSAORenderEffect = "SSAORenderEffect";
  61706. /**
  61707. * The horizontal blur PostProcess id in the pipeline
  61708. * @type {string}
  61709. */
  61710. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61711. /**
  61712. * The vertical blur PostProcess id in the pipeline
  61713. * @type {string}
  61714. */
  61715. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61716. /**
  61717. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61718. * @type {string}
  61719. */
  61720. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61721. /**
  61722. * The output strength of the SSAO post-process. Default value is 1.0.
  61723. * @type {number}
  61724. */
  61725. _this.totalStrength = 1.0;
  61726. /**
  61727. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  61728. * @type {number}
  61729. */
  61730. _this.radius = 0.0001;
  61731. /**
  61732. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  61733. * Must not be equal to fallOff and superior to fallOff.
  61734. * Default value is 0.975
  61735. * @type {number}
  61736. */
  61737. _this.area = 0.0075;
  61738. /**
  61739. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  61740. * Must not be equal to area and inferior to area.
  61741. * Default value is 0.0
  61742. * @type {number}
  61743. */
  61744. _this.fallOff = 0.000001;
  61745. /**
  61746. * The base color of the SSAO post-process
  61747. * The final result is "base + ssao" between [0, 1]
  61748. * @type {number}
  61749. */
  61750. _this.base = 0.5;
  61751. _this._firstUpdate = true;
  61752. _this._scene = scene;
  61753. // Set up assets
  61754. _this._createRandomTexture();
  61755. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  61756. var ssaoRatio = ratio.ssaoRatio || ratio;
  61757. var combineRatio = ratio.combineRatio || ratio;
  61758. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61759. _this._createSSAOPostProcess(ssaoRatio);
  61760. _this._createBlurPostProcess(ssaoRatio);
  61761. _this._createSSAOCombinePostProcess(combineRatio);
  61762. // Set up pipeline
  61763. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61764. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61766. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61767. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  61768. // Finish
  61769. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61770. if (cameras)
  61771. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61772. return _this;
  61773. }
  61774. // Public Methods
  61775. /**
  61776. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  61777. */
  61778. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  61779. if (disableDepthRender === void 0) { disableDepthRender = false; }
  61780. for (var i = 0; i < this._scene.cameras.length; i++) {
  61781. var camera = this._scene.cameras[i];
  61782. this._originalColorPostProcess.dispose(camera);
  61783. this._ssaoPostProcess.dispose(camera);
  61784. this._blurHPostProcess.dispose(camera);
  61785. this._blurVPostProcess.dispose(camera);
  61786. this._ssaoCombinePostProcess.dispose(camera);
  61787. }
  61788. this._randomTexture.dispose();
  61789. if (disableDepthRender)
  61790. this._scene.disableDepthRenderer();
  61791. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  61792. _super.prototype.dispose.call(this);
  61793. };
  61794. // Private Methods
  61795. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  61796. var _this = this;
  61797. var size = 16;
  61798. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61799. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61800. this._blurHPostProcess.onActivateObservable.add(function () {
  61801. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  61802. _this._blurHPostProcess.kernel = size * dw;
  61803. });
  61804. this._blurVPostProcess.onActivateObservable.add(function () {
  61805. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  61806. _this._blurVPostProcess.kernel = size * dw;
  61807. });
  61808. };
  61809. SSAORenderingPipeline.prototype._rebuild = function () {
  61810. this._firstUpdate = true;
  61811. _super.prototype._rebuild.call(this);
  61812. };
  61813. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  61814. var _this = this;
  61815. var numSamples = 16;
  61816. var sampleSphere = [
  61817. 0.5381, 0.1856, -0.4319,
  61818. 0.1379, 0.2486, 0.4430,
  61819. 0.3371, 0.5679, -0.0057,
  61820. -0.6999, -0.0451, -0.0019,
  61821. 0.0689, -0.1598, -0.8547,
  61822. 0.0560, 0.0069, -0.1843,
  61823. -0.0146, 0.1402, 0.0762,
  61824. 0.0100, -0.1924, -0.0344,
  61825. -0.3577, -0.5301, -0.4358,
  61826. -0.3169, 0.1063, 0.0158,
  61827. 0.0103, -0.5869, 0.0046,
  61828. -0.0897, -0.4940, 0.3287,
  61829. 0.7119, -0.0154, -0.0918,
  61830. -0.0533, 0.0596, -0.5411,
  61831. 0.0352, -0.0631, 0.5460,
  61832. -0.4776, 0.2847, -0.0271
  61833. ];
  61834. var samplesFactor = 1.0 / numSamples;
  61835. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  61836. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  61837. "area", "fallOff", "base", "range", "viewport"
  61838. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  61839. this._ssaoPostProcess.onApply = function (effect) {
  61840. if (_this._firstUpdate) {
  61841. effect.setArray3("sampleSphere", sampleSphere);
  61842. effect.setFloat("samplesFactor", samplesFactor);
  61843. effect.setFloat("randTextureTiles", 4.0);
  61844. }
  61845. effect.setFloat("totalStrength", _this.totalStrength);
  61846. effect.setFloat("radius", _this.radius);
  61847. effect.setFloat("area", _this.area);
  61848. effect.setFloat("fallOff", _this.fallOff);
  61849. effect.setFloat("base", _this.base);
  61850. effect.setTexture("textureSampler", _this._depthTexture);
  61851. effect.setTexture("randomSampler", _this._randomTexture);
  61852. };
  61853. };
  61854. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  61855. var _this = this;
  61856. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  61857. this._ssaoCombinePostProcess.onApply = function (effect) {
  61858. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  61859. };
  61860. };
  61861. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  61862. var size = 512;
  61863. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61864. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61865. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61866. var context = this._randomTexture.getContext();
  61867. var rand = function (min, max) {
  61868. return Math.random() * (max - min) + min;
  61869. };
  61870. var randVector = BABYLON.Vector3.Zero();
  61871. for (var x = 0; x < size; x++) {
  61872. for (var y = 0; y < size; y++) {
  61873. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  61874. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  61875. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  61876. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  61877. context.fillRect(x, y, 1, 1);
  61878. }
  61879. }
  61880. this._randomTexture.update(false);
  61881. };
  61882. __decorate([
  61883. BABYLON.serialize()
  61884. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  61885. __decorate([
  61886. BABYLON.serialize()
  61887. ], SSAORenderingPipeline.prototype, "radius", void 0);
  61888. __decorate([
  61889. BABYLON.serialize()
  61890. ], SSAORenderingPipeline.prototype, "area", void 0);
  61891. __decorate([
  61892. BABYLON.serialize()
  61893. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  61894. __decorate([
  61895. BABYLON.serialize()
  61896. ], SSAORenderingPipeline.prototype, "base", void 0);
  61897. return SSAORenderingPipeline;
  61898. }(BABYLON.PostProcessRenderPipeline));
  61899. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  61900. })(BABYLON || (BABYLON = {}));
  61901. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  61902. var BABYLON;
  61903. (function (BABYLON) {
  61904. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  61905. __extends(SSAO2RenderingPipeline, _super);
  61906. /**
  61907. * @constructor
  61908. * @param {string} name - The rendering pipeline name
  61909. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61910. * @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 }
  61911. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61912. */
  61913. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  61914. var _this = _super.call(this, scene.getEngine(), name) || this;
  61915. // Members
  61916. /**
  61917. * The PassPostProcess id in the pipeline that contains the original scene color
  61918. * @type {string}
  61919. */
  61920. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61921. /**
  61922. * The SSAO PostProcess id in the pipeline
  61923. * @type {string}
  61924. */
  61925. _this.SSAORenderEffect = "SSAORenderEffect";
  61926. /**
  61927. * The horizontal blur PostProcess id in the pipeline
  61928. * @type {string}
  61929. */
  61930. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61931. /**
  61932. * The vertical blur PostProcess id in the pipeline
  61933. * @type {string}
  61934. */
  61935. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61936. /**
  61937. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61938. * @type {string}
  61939. */
  61940. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61941. /**
  61942. * The output strength of the SSAO post-process. Default value is 1.0.
  61943. * @type {number}
  61944. */
  61945. _this.totalStrength = 1.0;
  61946. /**
  61947. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  61948. * @type {number}
  61949. */
  61950. _this.maxZ = 100.0;
  61951. /**
  61952. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  61953. * @type {number}
  61954. */
  61955. _this.minZAspect = 0.2;
  61956. /**
  61957. * Number of samples used for the SSAO calculations. Default value is 8
  61958. * @type {number}
  61959. */
  61960. _this._samples = 8;
  61961. /**
  61962. * Are we using bilateral blur ?
  61963. * @type {boolean}
  61964. */
  61965. _this._expensiveBlur = true;
  61966. /**
  61967. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  61968. * @type {number}
  61969. */
  61970. _this.radius = 2.0;
  61971. /**
  61972. * The base color of the SSAO post-process
  61973. * The final result is "base + ssao" between [0, 1]
  61974. * @type {number}
  61975. */
  61976. _this.base = 0.1;
  61977. _this._firstUpdate = true;
  61978. _this._scene = scene;
  61979. if (!_this.isSupported) {
  61980. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  61981. return _this;
  61982. }
  61983. var ssaoRatio = ratio.ssaoRatio || ratio;
  61984. var blurRatio = ratio.blurRatio || ratio;
  61985. // Set up assets
  61986. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  61987. _this._createRandomTexture();
  61988. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  61989. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  61990. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61991. _this._createSSAOPostProcess(1.0);
  61992. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  61993. _this._createSSAOCombinePostProcess(blurRatio);
  61994. // Set up pipeline
  61995. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61996. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61997. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61998. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61999. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62000. // Finish
  62001. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62002. if (cameras)
  62003. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62004. return _this;
  62005. }
  62006. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62007. get: function () {
  62008. return this._samples;
  62009. },
  62010. set: function (n) {
  62011. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  62012. this._samples = n;
  62013. this._sampleSphere = this._generateHemisphere();
  62014. this._firstUpdate = true;
  62015. },
  62016. enumerable: true,
  62017. configurable: true
  62018. });
  62019. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  62020. get: function () {
  62021. return this._expensiveBlur;
  62022. },
  62023. set: function (b) {
  62024. 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"]);
  62025. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  62026. this._expensiveBlur = b;
  62027. this._firstUpdate = true;
  62028. },
  62029. enumerable: true,
  62030. configurable: true
  62031. });
  62032. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  62033. /**
  62034. * Support test.
  62035. * @type {boolean}
  62036. */
  62037. get: function () {
  62038. var engine = BABYLON.Engine.LastCreatedEngine;
  62039. if (!engine) {
  62040. return false;
  62041. }
  62042. return engine.getCaps().drawBuffersExtension;
  62043. },
  62044. enumerable: true,
  62045. configurable: true
  62046. });
  62047. // Public Methods
  62048. /**
  62049. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62050. */
  62051. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  62052. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  62053. for (var i = 0; i < this._scene.cameras.length; i++) {
  62054. var camera = this._scene.cameras[i];
  62055. this._originalColorPostProcess.dispose(camera);
  62056. this._ssaoPostProcess.dispose(camera);
  62057. this._blurHPostProcess.dispose(camera);
  62058. this._blurVPostProcess.dispose(camera);
  62059. this._ssaoCombinePostProcess.dispose(camera);
  62060. }
  62061. this._randomTexture.dispose();
  62062. if (disableGeometryBufferRenderer)
  62063. this._scene.disableGeometryBufferRenderer();
  62064. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62065. _super.prototype.dispose.call(this);
  62066. };
  62067. // Private Methods
  62068. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  62069. var _this = this;
  62070. this._samplerOffsets = [];
  62071. var expensive = this.expensiveBlur;
  62072. for (var i = -8; i < 8; i++) {
  62073. this._samplerOffsets.push(i * 2 + 0.5);
  62074. }
  62075. 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");
  62076. this._blurHPostProcess.onApply = function (effect) {
  62077. if (!_this._scene.activeCamera) {
  62078. return;
  62079. }
  62080. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  62081. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62082. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62083. effect.setFloat("radius", _this.radius);
  62084. effect.setTexture("depthSampler", _this._depthTexture);
  62085. if (_this._firstUpdate) {
  62086. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62087. }
  62088. };
  62089. 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");
  62090. this._blurVPostProcess.onApply = function (effect) {
  62091. if (!_this._scene.activeCamera) {
  62092. return;
  62093. }
  62094. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  62095. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62096. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62097. effect.setFloat("radius", _this.radius);
  62098. effect.setTexture("depthSampler", _this._depthTexture);
  62099. if (_this._firstUpdate) {
  62100. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62101. _this._firstUpdate = false;
  62102. }
  62103. };
  62104. };
  62105. SSAO2RenderingPipeline.prototype._rebuild = function () {
  62106. this._firstUpdate = true;
  62107. _super.prototype._rebuild.call(this);
  62108. };
  62109. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  62110. var numSamples = this.samples;
  62111. var result = [];
  62112. var vector, scale;
  62113. var rand = function (min, max) {
  62114. return Math.random() * (max - min) + min;
  62115. };
  62116. var i = 0;
  62117. while (i < numSamples) {
  62118. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  62119. vector.normalize();
  62120. scale = i / numSamples;
  62121. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  62122. vector.scaleInPlace(scale);
  62123. result.push(vector.x, vector.y, vector.z);
  62124. i++;
  62125. }
  62126. return result;
  62127. };
  62128. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62129. var _this = this;
  62130. var numSamples = this.samples;
  62131. this._sampleSphere = this._generateHemisphere();
  62132. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  62133. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62134. "base", "range", "projection", "near", "far", "texelSize",
  62135. "xViewport", "yViewport", "maxZ", "minZAspect"
  62136. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62137. this._ssaoPostProcess.onApply = function (effect) {
  62138. if (_this._firstUpdate) {
  62139. effect.setArray3("sampleSphere", _this._sampleSphere);
  62140. effect.setFloat("randTextureTiles", 4.0);
  62141. }
  62142. if (!_this._scene.activeCamera) {
  62143. return;
  62144. }
  62145. effect.setFloat("samplesFactor", 1 / _this.samples);
  62146. effect.setFloat("totalStrength", _this.totalStrength);
  62147. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  62148. effect.setFloat("radius", _this.radius);
  62149. effect.setFloat("maxZ", _this.maxZ);
  62150. effect.setFloat("minZAspect", _this.minZAspect);
  62151. effect.setFloat("base", _this.base);
  62152. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62153. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62154. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  62155. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  62156. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  62157. effect.setTexture("textureSampler", _this._depthTexture);
  62158. effect.setTexture("normalSampler", _this._normalTexture);
  62159. effect.setTexture("randomSampler", _this._randomTexture);
  62160. };
  62161. };
  62162. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62163. var _this = this;
  62164. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62165. this._ssaoCombinePostProcess.onApply = function (effect) {
  62166. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62167. };
  62168. };
  62169. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  62170. var size = 512;
  62171. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62172. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62173. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62174. var context = this._randomTexture.getContext();
  62175. var rand = function (min, max) {
  62176. return Math.random() * (max - min) + min;
  62177. };
  62178. var randVector = BABYLON.Vector3.Zero();
  62179. for (var x = 0; x < size; x++) {
  62180. for (var y = 0; y < size; y++) {
  62181. randVector.x = rand(0.0, 1.0);
  62182. randVector.y = rand(0.0, 1.0);
  62183. randVector.z = 0.0;
  62184. randVector.normalize();
  62185. randVector.scaleInPlace(255);
  62186. randVector.x = Math.floor(randVector.x);
  62187. randVector.y = Math.floor(randVector.y);
  62188. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62189. context.fillRect(x, y, 1, 1);
  62190. }
  62191. }
  62192. this._randomTexture.update(false);
  62193. };
  62194. __decorate([
  62195. BABYLON.serialize()
  62196. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62197. __decorate([
  62198. BABYLON.serialize()
  62199. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62200. __decorate([
  62201. BABYLON.serialize()
  62202. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62203. __decorate([
  62204. BABYLON.serialize("samples")
  62205. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62206. __decorate([
  62207. BABYLON.serialize("expensiveBlur")
  62208. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62209. __decorate([
  62210. BABYLON.serialize()
  62211. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62212. __decorate([
  62213. BABYLON.serialize()
  62214. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62215. return SSAO2RenderingPipeline;
  62216. }(BABYLON.PostProcessRenderPipeline));
  62217. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62218. })(BABYLON || (BABYLON = {}));
  62219. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62220. // BABYLON.JS Chromatic Aberration GLSL Shader
  62221. // Author: Olivier Guyot
  62222. // Separates very slightly R, G and B colors on the edges of the screen
  62223. // Inspired by Francois Tarlier & Martins Upitis
  62224. var BABYLON;
  62225. (function (BABYLON) {
  62226. var LensRenderingPipeline = /** @class */ (function (_super) {
  62227. __extends(LensRenderingPipeline, _super);
  62228. /**
  62229. * @constructor
  62230. *
  62231. * Effect parameters are as follow:
  62232. * {
  62233. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62234. * edge_blur: number; // from 0 to x (1 for realism)
  62235. * distortion: number; // from 0 to x (1 for realism)
  62236. * grain_amount: number; // from 0 to 1
  62237. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62238. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62239. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62240. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62241. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62242. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62243. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62244. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62245. * }
  62246. * Note: if an effect parameter is unset, effect is disabled
  62247. *
  62248. * @param {string} name - The rendering pipeline name
  62249. * @param {object} parameters - An object containing all parameters (see above)
  62250. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62251. * @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)
  62252. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62253. */
  62254. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62255. if (ratio === void 0) { ratio = 1.0; }
  62256. var _this = _super.call(this, scene.getEngine(), name) || this;
  62257. // Lens effects can be of the following:
  62258. // - chromatic aberration (slight shift of RGB colors)
  62259. // - blur on the edge of the lens
  62260. // - lens distortion
  62261. // - depth-of-field blur & highlights enhancing
  62262. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62263. // - grain effect (noise or custom texture)
  62264. // Two additional texture samplers are needed:
  62265. // - depth map (for depth-of-field)
  62266. // - grain texture
  62267. /**
  62268. * The chromatic aberration PostProcess id in the pipeline
  62269. * @type {string}
  62270. */
  62271. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62272. /**
  62273. * The highlights enhancing PostProcess id in the pipeline
  62274. * @type {string}
  62275. */
  62276. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62277. /**
  62278. * The depth-of-field PostProcess id in the pipeline
  62279. * @type {string}
  62280. */
  62281. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62282. _this._scene = scene;
  62283. // Fetch texture samplers
  62284. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62285. if (parameters.grain_texture) {
  62286. _this._grainTexture = parameters.grain_texture;
  62287. }
  62288. else {
  62289. _this._createGrainTexture();
  62290. }
  62291. // save parameters
  62292. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62293. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62294. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62295. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62296. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62297. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62298. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62299. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62300. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62301. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62302. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62303. // Create effects
  62304. _this._createChromaticAberrationPostProcess(ratio);
  62305. _this._createHighlightsPostProcess(ratio);
  62306. _this._createDepthOfFieldPostProcess(ratio / 4);
  62307. // Set up pipeline
  62308. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62311. if (_this._highlightsGain === -1) {
  62312. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62313. }
  62314. // Finish
  62315. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62316. if (cameras) {
  62317. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62318. }
  62319. return _this;
  62320. }
  62321. // public methods (self explanatory)
  62322. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62323. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62324. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62325. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62326. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62327. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62328. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62329. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62330. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62331. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62332. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62333. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62334. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62335. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62336. };
  62337. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62338. this._highlightsPostProcess.updateEffect();
  62339. };
  62340. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62341. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62342. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62343. this._highlightsGain = amount;
  62344. };
  62345. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62346. if (this._highlightsGain === -1) {
  62347. this._highlightsGain = 1.0;
  62348. }
  62349. this._highlightsThreshold = amount;
  62350. };
  62351. LensRenderingPipeline.prototype.disableHighlights = function () {
  62352. this._highlightsGain = -1;
  62353. };
  62354. /**
  62355. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62356. */
  62357. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62358. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62359. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62360. this._chromaticAberrationPostProcess = null;
  62361. this._highlightsPostProcess = null;
  62362. this._depthOfFieldPostProcess = null;
  62363. this._grainTexture.dispose();
  62364. if (disableDepthRender)
  62365. this._scene.disableDepthRenderer();
  62366. };
  62367. // colors shifting and distortion
  62368. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62369. var _this = this;
  62370. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62371. [], // samplers
  62372. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62373. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62374. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62375. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62376. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62377. };
  62378. };
  62379. // highlights enhancing
  62380. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62381. var _this = this;
  62382. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62383. [], // samplers
  62384. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62385. this._highlightsPostProcess.onApply = function (effect) {
  62386. effect.setFloat('gain', _this._highlightsGain);
  62387. effect.setFloat('threshold', _this._highlightsThreshold);
  62388. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62389. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62390. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62391. };
  62392. };
  62393. // colors shifting and distortion
  62394. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62395. var _this = this;
  62396. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62397. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62398. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62399. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62400. this._depthOfFieldPostProcess.onApply = function (effect) {
  62401. effect.setTexture("depthSampler", _this._depthTexture);
  62402. effect.setTexture("grainSampler", _this._grainTexture);
  62403. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62404. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62405. effect.setFloat('grain_amount', _this._grainAmount);
  62406. effect.setBool('blur_noise', _this._blurNoise);
  62407. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62408. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62409. effect.setFloat('distortion', _this._distortion);
  62410. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  62411. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  62412. effect.setFloat('aperture', _this._dofAperture);
  62413. effect.setFloat('darken', _this._dofDarken);
  62414. effect.setFloat('edge_blur', _this._edgeBlur);
  62415. effect.setBool('highlights', (_this._highlightsGain !== -1));
  62416. if (_this._scene.activeCamera) {
  62417. effect.setFloat('near', _this._scene.activeCamera.minZ);
  62418. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  62419. }
  62420. };
  62421. };
  62422. // creates a black and white random noise texture, 512x512
  62423. LensRenderingPipeline.prototype._createGrainTexture = function () {
  62424. var size = 512;
  62425. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62426. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62427. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62428. var context = this._grainTexture.getContext();
  62429. var rand = function (min, max) {
  62430. return Math.random() * (max - min) + min;
  62431. };
  62432. var value;
  62433. for (var x = 0; x < size; x++) {
  62434. for (var y = 0; y < size; y++) {
  62435. value = Math.floor(rand(0.42, 0.58) * 255);
  62436. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  62437. context.fillRect(x, y, 1, 1);
  62438. }
  62439. }
  62440. this._grainTexture.update(false);
  62441. };
  62442. return LensRenderingPipeline;
  62443. }(BABYLON.PostProcessRenderPipeline));
  62444. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  62445. })(BABYLON || (BABYLON = {}));
  62446. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  62447. var BABYLON;
  62448. (function (BABYLON) {
  62449. var StandardRenderingPipeline = /** @class */ (function (_super) {
  62450. __extends(StandardRenderingPipeline, _super);
  62451. /**
  62452. * @constructor
  62453. * @param {string} name - The rendering pipeline name
  62454. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62455. * @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)
  62456. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62457. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62458. */
  62459. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62460. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62461. var _this = _super.call(this, scene.getEngine(), name) || this;
  62462. _this.downSampleX4PostProcess = null;
  62463. _this.brightPassPostProcess = null;
  62464. _this.blurHPostProcesses = [];
  62465. _this.blurVPostProcesses = [];
  62466. _this.textureAdderPostProcess = null;
  62467. _this.volumetricLightPostProcess = null;
  62468. _this.volumetricLightSmoothXPostProcess = null;
  62469. _this.volumetricLightSmoothYPostProcess = null;
  62470. _this.volumetricLightMergePostProces = null;
  62471. _this.volumetricLightFinalPostProcess = null;
  62472. _this.luminancePostProcess = null;
  62473. _this.luminanceDownSamplePostProcesses = [];
  62474. _this.hdrPostProcess = null;
  62475. _this.textureAdderFinalPostProcess = null;
  62476. _this.lensFlareFinalPostProcess = null;
  62477. _this.hdrFinalPostProcess = null;
  62478. _this.lensFlarePostProcess = null;
  62479. _this.lensFlareComposePostProcess = null;
  62480. _this.motionBlurPostProcess = null;
  62481. _this.depthOfFieldPostProcess = null;
  62482. // Values
  62483. _this.brightThreshold = 1.0;
  62484. _this.blurWidth = 512.0;
  62485. _this.horizontalBlur = false;
  62486. _this.exposure = 1.0;
  62487. _this.lensTexture = null;
  62488. _this.volumetricLightCoefficient = 0.2;
  62489. _this.volumetricLightPower = 4.0;
  62490. _this.volumetricLightBlurScale = 64.0;
  62491. _this.sourceLight = null;
  62492. _this.hdrMinimumLuminance = 1.0;
  62493. _this.hdrDecreaseRate = 0.5;
  62494. _this.hdrIncreaseRate = 0.5;
  62495. _this.lensColorTexture = null;
  62496. _this.lensFlareStrength = 20.0;
  62497. _this.lensFlareGhostDispersal = 1.4;
  62498. _this.lensFlareHaloWidth = 0.7;
  62499. _this.lensFlareDistortionStrength = 16.0;
  62500. _this.lensStarTexture = null;
  62501. _this.lensFlareDirtTexture = null;
  62502. _this.depthOfFieldDistance = 10.0;
  62503. _this.depthOfFieldBlurWidth = 64.0;
  62504. _this.motionStrength = 1.0;
  62505. // IAnimatable
  62506. _this.animations = [];
  62507. _this._currentDepthOfFieldSource = null;
  62508. _this._hdrCurrentLuminance = 1.0;
  62509. // Getters and setters
  62510. _this._bloomEnabled = true;
  62511. _this._depthOfFieldEnabled = false;
  62512. _this._vlsEnabled = false;
  62513. _this._lensFlareEnabled = false;
  62514. _this._hdrEnabled = false;
  62515. _this._motionBlurEnabled = false;
  62516. _this._motionBlurSamples = 64.0;
  62517. _this._volumetricLightStepsCount = 50.0;
  62518. _this._cameras = cameras || [];
  62519. // Initialize
  62520. _this._scene = scene;
  62521. _this._basePostProcess = originalPostProcess;
  62522. _this._ratio = ratio;
  62523. // Misc
  62524. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62525. // Finish
  62526. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62527. _this._buildPipeline();
  62528. return _this;
  62529. }
  62530. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  62531. get: function () {
  62532. return this._bloomEnabled;
  62533. },
  62534. set: function (enabled) {
  62535. if (this._bloomEnabled === enabled) {
  62536. return;
  62537. }
  62538. this._bloomEnabled = enabled;
  62539. this._buildPipeline();
  62540. },
  62541. enumerable: true,
  62542. configurable: true
  62543. });
  62544. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62545. get: function () {
  62546. return this._depthOfFieldEnabled;
  62547. },
  62548. set: function (enabled) {
  62549. if (this._depthOfFieldEnabled === enabled) {
  62550. return;
  62551. }
  62552. this._depthOfFieldEnabled = enabled;
  62553. this._buildPipeline();
  62554. },
  62555. enumerable: true,
  62556. configurable: true
  62557. });
  62558. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  62559. get: function () {
  62560. return this._lensFlareEnabled;
  62561. },
  62562. set: function (enabled) {
  62563. if (this._lensFlareEnabled === enabled) {
  62564. return;
  62565. }
  62566. this._lensFlareEnabled = enabled;
  62567. this._buildPipeline();
  62568. },
  62569. enumerable: true,
  62570. configurable: true
  62571. });
  62572. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  62573. get: function () {
  62574. return this._hdrEnabled;
  62575. },
  62576. set: function (enabled) {
  62577. if (this._hdrEnabled === enabled) {
  62578. return;
  62579. }
  62580. this._hdrEnabled = enabled;
  62581. this._buildPipeline();
  62582. },
  62583. enumerable: true,
  62584. configurable: true
  62585. });
  62586. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  62587. get: function () {
  62588. return this._vlsEnabled;
  62589. },
  62590. set: function (enabled) {
  62591. if (this._vlsEnabled === enabled) {
  62592. return;
  62593. }
  62594. if (enabled) {
  62595. var geometry = this._scene.enableGeometryBufferRenderer();
  62596. if (!geometry) {
  62597. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  62598. return;
  62599. }
  62600. }
  62601. this._vlsEnabled = enabled;
  62602. this._buildPipeline();
  62603. },
  62604. enumerable: true,
  62605. configurable: true
  62606. });
  62607. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  62608. get: function () {
  62609. return this._motionBlurEnabled;
  62610. },
  62611. set: function (enabled) {
  62612. if (this._motionBlurEnabled === enabled) {
  62613. return;
  62614. }
  62615. this._motionBlurEnabled = enabled;
  62616. this._buildPipeline();
  62617. },
  62618. enumerable: true,
  62619. configurable: true
  62620. });
  62621. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  62622. get: function () {
  62623. return this._volumetricLightStepsCount;
  62624. },
  62625. set: function (count) {
  62626. if (this.volumetricLightPostProcess) {
  62627. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  62628. }
  62629. this._volumetricLightStepsCount = count;
  62630. },
  62631. enumerable: true,
  62632. configurable: true
  62633. });
  62634. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  62635. get: function () {
  62636. return this._motionBlurSamples;
  62637. },
  62638. set: function (samples) {
  62639. if (this.motionBlurPostProcess) {
  62640. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  62641. }
  62642. this._motionBlurSamples = samples;
  62643. },
  62644. enumerable: true,
  62645. configurable: true
  62646. });
  62647. StandardRenderingPipeline.prototype._buildPipeline = function () {
  62648. var _this = this;
  62649. var ratio = this._ratio;
  62650. var scene = this._scene;
  62651. this._disposePostProcesses();
  62652. this._reset();
  62653. // Create pass post-process
  62654. if (!this._basePostProcess) {
  62655. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  62656. this.originalPostProcess.onApply = function (effect) {
  62657. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  62658. };
  62659. }
  62660. else {
  62661. this.originalPostProcess = this._basePostProcess;
  62662. }
  62663. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  62664. this._currentDepthOfFieldSource = this.originalPostProcess;
  62665. if (this._vlsEnabled) {
  62666. // Create volumetric light
  62667. this._createVolumetricLightPostProcess(scene, ratio);
  62668. // Create volumetric light final post-process
  62669. 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);
  62670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  62671. }
  62672. if (this._bloomEnabled) {
  62673. // Create down sample X4 post-process
  62674. this._createDownSampleX4PostProcess(scene, ratio / 2);
  62675. // Create bright pass post-process
  62676. this._createBrightPassPostProcess(scene, ratio / 2);
  62677. // Create gaussian blur post-processes (down sampling blurs)
  62678. this._createBlurPostProcesses(scene, ratio / 4, 1);
  62679. // Create texture adder post-process
  62680. this._createTextureAdderPostProcess(scene, ratio);
  62681. // Create depth-of-field source post-process
  62682. 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);
  62683. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  62684. }
  62685. if (this._lensFlareEnabled) {
  62686. // Create lens flare post-process
  62687. this._createLensFlarePostProcess(scene, ratio);
  62688. // Create depth-of-field source post-process post lens-flare and disable it now
  62689. 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);
  62690. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  62691. }
  62692. if (this._hdrEnabled) {
  62693. // Create luminance
  62694. this._createLuminancePostProcesses(scene, this._floatTextureType);
  62695. // Create HDR
  62696. this._createHdrPostProcess(scene, ratio);
  62697. // Create depth-of-field source post-process post hdr and disable it now
  62698. 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);
  62699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  62700. }
  62701. if (this._depthOfFieldEnabled) {
  62702. // Create gaussian blur used by depth-of-field
  62703. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  62704. // Create depth-of-field post-process
  62705. this._createDepthOfFieldPostProcess(scene, ratio);
  62706. }
  62707. if (this._motionBlurEnabled) {
  62708. // Create motion blur post-process
  62709. this._createMotionBlurPostProcess(scene, ratio);
  62710. }
  62711. if (this._cameras !== null) {
  62712. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  62713. }
  62714. };
  62715. // Down Sample X4 Post-Processs
  62716. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  62717. var _this = this;
  62718. var downSampleX4Offsets = new Array(32);
  62719. 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);
  62720. this.downSampleX4PostProcess.onApply = function (effect) {
  62721. var id = 0;
  62722. var width = _this.downSampleX4PostProcess.width;
  62723. var height = _this.downSampleX4PostProcess.height;
  62724. for (var i = -2; i < 2; i++) {
  62725. for (var j = -2; j < 2; j++) {
  62726. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  62727. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  62728. id += 2;
  62729. }
  62730. }
  62731. effect.setArray2("dsOffsets", downSampleX4Offsets);
  62732. };
  62733. // Add to pipeline
  62734. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  62735. };
  62736. // Brightpass Post-Process
  62737. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  62738. var _this = this;
  62739. var brightOffsets = new Array(8);
  62740. 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);
  62741. this.brightPassPostProcess.onApply = function (effect) {
  62742. var sU = (1.0 / _this.brightPassPostProcess.width);
  62743. var sV = (1.0 / _this.brightPassPostProcess.height);
  62744. brightOffsets[0] = -0.5 * sU;
  62745. brightOffsets[1] = 0.5 * sV;
  62746. brightOffsets[2] = 0.5 * sU;
  62747. brightOffsets[3] = 0.5 * sV;
  62748. brightOffsets[4] = -0.5 * sU;
  62749. brightOffsets[5] = -0.5 * sV;
  62750. brightOffsets[6] = 0.5 * sU;
  62751. brightOffsets[7] = -0.5 * sV;
  62752. effect.setArray2("dsOffsets", brightOffsets);
  62753. effect.setFloat("brightThreshold", _this.brightThreshold);
  62754. };
  62755. // Add to pipeline
  62756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  62757. };
  62758. // Create blur H&V post-processes
  62759. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  62760. var _this = this;
  62761. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  62762. var engine = scene.getEngine();
  62763. 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);
  62764. 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);
  62765. blurX.onActivateObservable.add(function () {
  62766. var dw = blurX.width / engine.getRenderWidth();
  62767. blurX.kernel = _this[blurWidthKey] * dw;
  62768. });
  62769. blurY.onActivateObservable.add(function () {
  62770. var dw = blurY.height / engine.getRenderHeight();
  62771. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  62772. });
  62773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  62774. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  62775. this.blurHPostProcesses.push(blurX);
  62776. this.blurVPostProcesses.push(blurY);
  62777. };
  62778. // Create texture adder post-process
  62779. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62780. var _this = this;
  62781. 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);
  62782. this.textureAdderPostProcess.onApply = function (effect) {
  62783. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  62784. effect.setTexture("lensSampler", _this.lensTexture);
  62785. effect.setFloat("exposure", _this.exposure);
  62786. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  62787. };
  62788. // Add to pipeline
  62789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62790. };
  62791. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  62792. var _this = this;
  62793. var geometryRenderer = scene.enableGeometryBufferRenderer();
  62794. geometryRenderer.enablePosition = true;
  62795. var geometry = geometryRenderer.getGBuffer();
  62796. // Base post-process
  62797. 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));
  62798. var depthValues = BABYLON.Vector2.Zero();
  62799. this.volumetricLightPostProcess.onApply = function (effect) {
  62800. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  62801. var generator = _this.sourceLight.getShadowGenerator();
  62802. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  62803. effect.setTexture("positionSampler", geometry.textures[2]);
  62804. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  62805. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  62806. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  62807. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  62808. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  62809. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  62810. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  62811. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  62812. effect.setVector2("depthValues", depthValues);
  62813. }
  62814. };
  62815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  62816. // Smooth
  62817. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  62818. // Merge
  62819. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  62820. this.volumetricLightMergePostProces.onApply = function (effect) {
  62821. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  62822. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  62823. };
  62824. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  62825. };
  62826. // Create luminance
  62827. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  62828. var _this = this;
  62829. // Create luminance
  62830. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  62831. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  62832. var offsets = [];
  62833. this.luminancePostProcess.onApply = function (effect) {
  62834. var sU = (1.0 / _this.luminancePostProcess.width);
  62835. var sV = (1.0 / _this.luminancePostProcess.height);
  62836. offsets[0] = -0.5 * sU;
  62837. offsets[1] = 0.5 * sV;
  62838. offsets[2] = 0.5 * sU;
  62839. offsets[3] = 0.5 * sV;
  62840. offsets[4] = -0.5 * sU;
  62841. offsets[5] = -0.5 * sV;
  62842. offsets[6] = 0.5 * sU;
  62843. offsets[7] = -0.5 * sV;
  62844. effect.setArray2("lumOffsets", offsets);
  62845. };
  62846. // Add to pipeline
  62847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  62848. // Create down sample luminance
  62849. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  62850. var size = Math.pow(3, i);
  62851. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  62852. if (i === 0) {
  62853. defines += "#define FINAL_DOWN_SAMPLER";
  62854. }
  62855. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  62856. this.luminanceDownSamplePostProcesses.push(postProcess);
  62857. }
  62858. // Create callbacks and add effects
  62859. var lastLuminance = this.luminancePostProcess;
  62860. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  62861. var downSampleOffsets = new Array(18);
  62862. pp.onApply = function (effect) {
  62863. if (!lastLuminance) {
  62864. return;
  62865. }
  62866. var id = 0;
  62867. for (var x = -1; x < 2; x++) {
  62868. for (var y = -1; y < 2; y++) {
  62869. downSampleOffsets[id] = x / lastLuminance.width;
  62870. downSampleOffsets[id + 1] = y / lastLuminance.height;
  62871. id += 2;
  62872. }
  62873. }
  62874. effect.setArray2("dsOffsets", downSampleOffsets);
  62875. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  62876. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62877. lastLuminance = _this.luminancePostProcess;
  62878. }
  62879. else {
  62880. lastLuminance = pp;
  62881. }
  62882. };
  62883. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62884. pp.onAfterRender = function (effect) {
  62885. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  62886. 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);
  62887. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  62888. };
  62889. }
  62890. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  62891. });
  62892. };
  62893. // Create HDR post-process
  62894. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  62895. var _this = this;
  62896. 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);
  62897. var outputLiminance = 1;
  62898. var time = 0;
  62899. var lastTime = 0;
  62900. this.hdrPostProcess.onApply = function (effect) {
  62901. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  62902. time += scene.getEngine().getDeltaTime();
  62903. if (outputLiminance < 0) {
  62904. outputLiminance = _this._hdrCurrentLuminance;
  62905. }
  62906. else {
  62907. var dt = (lastTime - time) / 1000.0;
  62908. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  62909. outputLiminance += _this.hdrDecreaseRate * dt;
  62910. }
  62911. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  62912. outputLiminance -= _this.hdrIncreaseRate * dt;
  62913. }
  62914. else {
  62915. outputLiminance = _this._hdrCurrentLuminance;
  62916. }
  62917. }
  62918. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  62919. effect.setFloat("averageLuminance", outputLiminance);
  62920. lastTime = time;
  62921. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  62922. };
  62923. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  62924. };
  62925. // Create lens flare post-process
  62926. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  62927. var _this = this;
  62928. 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);
  62929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  62930. this._createBlurPostProcesses(scene, ratio / 4, 2);
  62931. 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);
  62932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  62933. var resolution = new BABYLON.Vector2(0, 0);
  62934. // Lens flare
  62935. this.lensFlarePostProcess.onApply = function (effect) {
  62936. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  62937. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  62938. effect.setFloat("strength", _this.lensFlareStrength);
  62939. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  62940. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  62941. // Shift
  62942. resolution.x = _this.lensFlarePostProcess.width;
  62943. resolution.y = _this.lensFlarePostProcess.height;
  62944. effect.setVector2("resolution", resolution);
  62945. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  62946. };
  62947. // Compose
  62948. 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);
  62949. 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);
  62950. this.lensFlareComposePostProcess.onApply = function (effect) {
  62951. if (!_this._scene.activeCamera) {
  62952. return;
  62953. }
  62954. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62955. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  62956. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  62957. // Lens start rotation matrix
  62958. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  62959. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  62960. 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));
  62961. camRot *= 4.0;
  62962. 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);
  62963. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  62964. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  62965. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  62966. };
  62967. };
  62968. // Create depth-of-field post-process
  62969. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62970. var _this = this;
  62971. 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);
  62972. this.depthOfFieldPostProcess.onApply = function (effect) {
  62973. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62974. effect.setTexture("depthSampler", _this._getDepthTexture());
  62975. effect.setFloat("distance", _this.depthOfFieldDistance);
  62976. };
  62977. // Add to pipeline
  62978. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62979. };
  62980. // Create motion blur post-process
  62981. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  62982. var _this = this;
  62983. 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);
  62984. var motionScale = 0;
  62985. var prevViewProjection = BABYLON.Matrix.Identity();
  62986. var invViewProjection = BABYLON.Matrix.Identity();
  62987. var viewProjection = BABYLON.Matrix.Identity();
  62988. var screenSize = BABYLON.Vector2.Zero();
  62989. this.motionBlurPostProcess.onApply = function (effect) {
  62990. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  62991. viewProjection.invertToRef(invViewProjection);
  62992. effect.setMatrix("inverseViewProjection", invViewProjection);
  62993. effect.setMatrix("prevViewProjection", prevViewProjection);
  62994. prevViewProjection = viewProjection;
  62995. screenSize.x = _this.motionBlurPostProcess.width;
  62996. screenSize.y = _this.motionBlurPostProcess.height;
  62997. effect.setVector2("screenSize", screenSize);
  62998. motionScale = scene.getEngine().getFps() / 60.0;
  62999. effect.setFloat("motionScale", motionScale);
  63000. effect.setFloat("motionStrength", _this.motionStrength);
  63001. effect.setTexture("depthSampler", _this._getDepthTexture());
  63002. };
  63003. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63004. };
  63005. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63006. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63007. var renderer = this._scene.enableGeometryBufferRenderer();
  63008. return renderer.getGBuffer().textures[0];
  63009. }
  63010. return this._scene.enableDepthRenderer().getDepthMap();
  63011. };
  63012. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  63013. for (var i = 0; i < this._cameras.length; i++) {
  63014. var camera = this._cameras[i];
  63015. if (this.originalPostProcess) {
  63016. this.originalPostProcess.dispose(camera);
  63017. }
  63018. if (this.downSampleX4PostProcess) {
  63019. this.downSampleX4PostProcess.dispose(camera);
  63020. }
  63021. if (this.brightPassPostProcess) {
  63022. this.brightPassPostProcess.dispose(camera);
  63023. }
  63024. if (this.textureAdderPostProcess) {
  63025. this.textureAdderPostProcess.dispose(camera);
  63026. }
  63027. if (this.textureAdderFinalPostProcess) {
  63028. this.textureAdderFinalPostProcess.dispose(camera);
  63029. }
  63030. if (this.volumetricLightPostProcess) {
  63031. this.volumetricLightPostProcess.dispose(camera);
  63032. }
  63033. if (this.volumetricLightSmoothXPostProcess) {
  63034. this.volumetricLightSmoothXPostProcess.dispose(camera);
  63035. }
  63036. if (this.volumetricLightSmoothYPostProcess) {
  63037. this.volumetricLightSmoothYPostProcess.dispose(camera);
  63038. }
  63039. if (this.volumetricLightMergePostProces) {
  63040. this.volumetricLightMergePostProces.dispose(camera);
  63041. }
  63042. if (this.volumetricLightFinalPostProcess) {
  63043. this.volumetricLightFinalPostProcess.dispose(camera);
  63044. }
  63045. if (this.lensFlarePostProcess) {
  63046. this.lensFlarePostProcess.dispose(camera);
  63047. }
  63048. if (this.lensFlareComposePostProcess) {
  63049. this.lensFlareComposePostProcess.dispose(camera);
  63050. }
  63051. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  63052. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  63053. }
  63054. if (this.luminancePostProcess) {
  63055. this.luminancePostProcess.dispose(camera);
  63056. }
  63057. if (this.hdrPostProcess) {
  63058. this.hdrPostProcess.dispose(camera);
  63059. }
  63060. if (this.hdrFinalPostProcess) {
  63061. this.hdrFinalPostProcess.dispose(camera);
  63062. }
  63063. if (this.depthOfFieldPostProcess) {
  63064. this.depthOfFieldPostProcess.dispose(camera);
  63065. }
  63066. if (this.motionBlurPostProcess) {
  63067. this.motionBlurPostProcess.dispose(camera);
  63068. }
  63069. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  63070. this.blurHPostProcesses[j].dispose(camera);
  63071. }
  63072. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  63073. this.blurVPostProcesses[j].dispose(camera);
  63074. }
  63075. }
  63076. this.originalPostProcess = null;
  63077. this.downSampleX4PostProcess = null;
  63078. this.brightPassPostProcess = null;
  63079. this.textureAdderPostProcess = null;
  63080. this.textureAdderFinalPostProcess = null;
  63081. this.volumetricLightPostProcess = null;
  63082. this.volumetricLightSmoothXPostProcess = null;
  63083. this.volumetricLightSmoothYPostProcess = null;
  63084. this.volumetricLightMergePostProces = null;
  63085. this.volumetricLightFinalPostProcess = null;
  63086. this.lensFlarePostProcess = null;
  63087. this.lensFlareComposePostProcess = null;
  63088. this.luminancePostProcess = null;
  63089. this.hdrPostProcess = null;
  63090. this.hdrFinalPostProcess = null;
  63091. this.depthOfFieldPostProcess = null;
  63092. this.motionBlurPostProcess = null;
  63093. this.luminanceDownSamplePostProcesses = [];
  63094. this.blurHPostProcesses = [];
  63095. this.blurVPostProcesses = [];
  63096. };
  63097. // Dispose
  63098. StandardRenderingPipeline.prototype.dispose = function () {
  63099. this._disposePostProcesses();
  63100. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63101. _super.prototype.dispose.call(this);
  63102. };
  63103. // Serialize rendering pipeline
  63104. StandardRenderingPipeline.prototype.serialize = function () {
  63105. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63106. serializationObject.customType = "StandardRenderingPipeline";
  63107. return serializationObject;
  63108. };
  63109. /**
  63110. * Static members
  63111. */
  63112. // Parse serialized pipeline
  63113. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63114. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  63115. };
  63116. // Luminance steps
  63117. StandardRenderingPipeline.LuminanceSteps = 6;
  63118. __decorate([
  63119. BABYLON.serialize()
  63120. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  63121. __decorate([
  63122. BABYLON.serialize()
  63123. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  63124. __decorate([
  63125. BABYLON.serialize()
  63126. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  63127. __decorate([
  63128. BABYLON.serialize()
  63129. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  63130. __decorate([
  63131. BABYLON.serializeAsTexture("lensTexture")
  63132. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  63133. __decorate([
  63134. BABYLON.serialize()
  63135. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  63136. __decorate([
  63137. BABYLON.serialize()
  63138. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  63139. __decorate([
  63140. BABYLON.serialize()
  63141. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  63142. __decorate([
  63143. BABYLON.serialize()
  63144. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  63145. __decorate([
  63146. BABYLON.serialize()
  63147. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  63148. __decorate([
  63149. BABYLON.serialize()
  63150. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  63151. __decorate([
  63152. BABYLON.serializeAsTexture("lensColorTexture")
  63153. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  63154. __decorate([
  63155. BABYLON.serialize()
  63156. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  63157. __decorate([
  63158. BABYLON.serialize()
  63159. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  63160. __decorate([
  63161. BABYLON.serialize()
  63162. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  63163. __decorate([
  63164. BABYLON.serialize()
  63165. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  63166. __decorate([
  63167. BABYLON.serializeAsTexture("lensStarTexture")
  63168. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  63169. __decorate([
  63170. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  63171. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  63172. __decorate([
  63173. BABYLON.serialize()
  63174. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  63175. __decorate([
  63176. BABYLON.serialize()
  63177. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63178. __decorate([
  63179. BABYLON.serialize()
  63180. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63181. __decorate([
  63182. BABYLON.serialize()
  63183. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63184. __decorate([
  63185. BABYLON.serialize()
  63186. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63187. __decorate([
  63188. BABYLON.serialize()
  63189. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63190. __decorate([
  63191. BABYLON.serialize()
  63192. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63193. __decorate([
  63194. BABYLON.serialize()
  63195. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63196. __decorate([
  63197. BABYLON.serialize()
  63198. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63199. __decorate([
  63200. BABYLON.serialize()
  63201. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63202. __decorate([
  63203. BABYLON.serialize()
  63204. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63205. __decorate([
  63206. BABYLON.serialize()
  63207. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63208. return StandardRenderingPipeline;
  63209. }(BABYLON.PostProcessRenderPipeline));
  63210. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63211. })(BABYLON || (BABYLON = {}));
  63212. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63213. var BABYLON;
  63214. (function (BABYLON) {
  63215. var FxaaPostProcess = /** @class */ (function (_super) {
  63216. __extends(FxaaPostProcess, _super);
  63217. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63218. if (camera === void 0) { camera = null; }
  63219. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63220. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63221. _this.onApplyObservable.add(function (effect) {
  63222. var texelSize = _this.texelSize;
  63223. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63224. });
  63225. return _this;
  63226. }
  63227. return FxaaPostProcess;
  63228. }(BABYLON.PostProcess));
  63229. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63230. })(BABYLON || (BABYLON = {}));
  63231. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63232. var BABYLON;
  63233. (function (BABYLON) {
  63234. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63235. __extends(DefaultRenderingPipeline, _super);
  63236. /**
  63237. * @constructor
  63238. * @param {string} name - The rendering pipeline name
  63239. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63240. * @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)
  63241. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63242. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63243. */
  63244. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63245. if (automaticBuild === void 0) { automaticBuild = true; }
  63246. var _this = _super.call(this, scene.getEngine(), name) || this;
  63247. _this.PassPostProcessId = "PassPostProcessEffect";
  63248. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63249. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63250. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63251. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63252. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63253. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63254. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63255. // IAnimatable
  63256. _this.animations = [];
  63257. // Values
  63258. _this._bloomEnabled = false;
  63259. _this._fxaaEnabled = false;
  63260. _this._imageProcessingEnabled = true;
  63261. _this._bloomScale = 0.6;
  63262. _this._buildAllowed = true;
  63263. /**
  63264. * Specifies the size of the bloom blur kernel, relative to the final output size
  63265. */
  63266. _this.bloomKernel = 64;
  63267. /**
  63268. * Specifies the weight of the bloom in the final rendering
  63269. */
  63270. _this._bloomWeight = 0.15;
  63271. _this._cameras = cameras || [];
  63272. _this._buildAllowed = automaticBuild;
  63273. // Initialize
  63274. _this._scene = scene;
  63275. var caps = _this._scene.getEngine().getCaps();
  63276. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63277. // Misc
  63278. if (_this._hdr) {
  63279. if (caps.textureHalfFloatRender) {
  63280. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63281. }
  63282. else if (caps.textureFloatRender) {
  63283. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63284. }
  63285. }
  63286. else {
  63287. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63288. }
  63289. // Attach
  63290. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63291. _this._buildPipeline();
  63292. return _this;
  63293. }
  63294. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63295. get: function () {
  63296. return this._bloomWeight;
  63297. },
  63298. set: function (value) {
  63299. if (this._bloomWeight === value) {
  63300. return;
  63301. }
  63302. this._bloomWeight = value;
  63303. if (this._hdr && this.copyBack) {
  63304. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63305. }
  63306. },
  63307. enumerable: true,
  63308. configurable: true
  63309. });
  63310. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63311. get: function () {
  63312. return this._bloomScale;
  63313. },
  63314. set: function (value) {
  63315. if (this._bloomScale === value) {
  63316. return;
  63317. }
  63318. this._bloomScale = value;
  63319. this._buildPipeline();
  63320. },
  63321. enumerable: true,
  63322. configurable: true
  63323. });
  63324. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63325. get: function () {
  63326. return this._bloomEnabled;
  63327. },
  63328. set: function (enabled) {
  63329. if (this._bloomEnabled === enabled) {
  63330. return;
  63331. }
  63332. this._bloomEnabled = enabled;
  63333. this._buildPipeline();
  63334. },
  63335. enumerable: true,
  63336. configurable: true
  63337. });
  63338. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63339. get: function () {
  63340. return this._fxaaEnabled;
  63341. },
  63342. set: function (enabled) {
  63343. if (this._fxaaEnabled === enabled) {
  63344. return;
  63345. }
  63346. this._fxaaEnabled = enabled;
  63347. this._buildPipeline();
  63348. },
  63349. enumerable: true,
  63350. configurable: true
  63351. });
  63352. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63353. get: function () {
  63354. return this._imageProcessingEnabled;
  63355. },
  63356. set: function (enabled) {
  63357. if (this._imageProcessingEnabled === enabled) {
  63358. return;
  63359. }
  63360. this._imageProcessingEnabled = enabled;
  63361. this._buildPipeline();
  63362. },
  63363. enumerable: true,
  63364. configurable: true
  63365. });
  63366. /**
  63367. * Force the compilation of the entire pipeline.
  63368. */
  63369. DefaultRenderingPipeline.prototype.prepare = function () {
  63370. var previousState = this._buildAllowed;
  63371. this._buildAllowed = true;
  63372. this._buildPipeline();
  63373. this._buildAllowed = previousState;
  63374. };
  63375. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63376. var _this = this;
  63377. if (!this._buildAllowed) {
  63378. return;
  63379. }
  63380. var engine = this._scene.getEngine();
  63381. this._disposePostProcesses();
  63382. this._reset();
  63383. if (this.bloomEnabled) {
  63384. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63385. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63386. if (!this._hdr) {
  63387. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63388. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63389. this.highlights.autoClear = false;
  63390. this.highlights.alwaysForcePOT = true;
  63391. }
  63392. 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);
  63393. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63394. this.blurX.alwaysForcePOT = true;
  63395. this.blurX.autoClear = false;
  63396. this.blurX.onActivateObservable.add(function () {
  63397. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63398. _this.blurX.kernel = _this.bloomKernel * dw;
  63399. });
  63400. 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);
  63401. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63402. this.blurY.alwaysForcePOT = true;
  63403. this.blurY.autoClear = false;
  63404. this.blurY.onActivateObservable.add(function () {
  63405. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63406. _this.blurY.kernel = _this.bloomKernel * dh;
  63407. });
  63408. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63409. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  63410. this.copyBack.alwaysForcePOT = true;
  63411. if (this._hdr) {
  63412. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  63413. var w = this.bloomWeight;
  63414. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  63415. }
  63416. else {
  63417. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  63418. }
  63419. this.copyBack.autoClear = false;
  63420. }
  63421. if (this._imageProcessingEnabled) {
  63422. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63423. if (this._hdr) {
  63424. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  63425. }
  63426. else {
  63427. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  63428. }
  63429. }
  63430. if (this.fxaaEnabled) {
  63431. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63432. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  63433. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63434. }
  63435. else if (this._hdr && this.imageProcessing) {
  63436. this.finalMerge = this.imageProcessing;
  63437. }
  63438. else {
  63439. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63440. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  63441. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63442. }
  63443. if (this.bloomEnabled) {
  63444. if (this._hdr) {
  63445. this.copyBack.shareOutputWith(this.blurX);
  63446. if (this.imageProcessing) {
  63447. this.imageProcessing.shareOutputWith(this.pass);
  63448. this.imageProcessing.autoClear = false;
  63449. }
  63450. else if (this.fxaa) {
  63451. this.fxaa.shareOutputWith(this.pass);
  63452. }
  63453. else {
  63454. this.finalMerge.shareOutputWith(this.pass);
  63455. }
  63456. }
  63457. else {
  63458. if (this.fxaa) {
  63459. this.fxaa.shareOutputWith(this.pass);
  63460. }
  63461. else {
  63462. this.finalMerge.shareOutputWith(this.pass);
  63463. }
  63464. }
  63465. }
  63466. if (this._cameras !== null) {
  63467. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63468. }
  63469. };
  63470. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  63471. for (var i = 0; i < this._cameras.length; i++) {
  63472. var camera = this._cameras[i];
  63473. if (this.pass) {
  63474. this.pass.dispose(camera);
  63475. }
  63476. if (this.highlights) {
  63477. this.highlights.dispose(camera);
  63478. }
  63479. if (this.blurX) {
  63480. this.blurX.dispose(camera);
  63481. }
  63482. if (this.blurY) {
  63483. this.blurY.dispose(camera);
  63484. }
  63485. if (this.copyBack) {
  63486. this.copyBack.dispose(camera);
  63487. }
  63488. if (this.imageProcessing) {
  63489. this.imageProcessing.dispose(camera);
  63490. }
  63491. if (this.fxaa) {
  63492. this.fxaa.dispose(camera);
  63493. }
  63494. if (this.finalMerge) {
  63495. this.finalMerge.dispose(camera);
  63496. }
  63497. }
  63498. this.pass = null;
  63499. this.highlights = null;
  63500. this.blurX = null;
  63501. this.blurY = null;
  63502. this.copyBack = null;
  63503. this.imageProcessing = null;
  63504. this.fxaa = null;
  63505. this.finalMerge = null;
  63506. };
  63507. // Dispose
  63508. DefaultRenderingPipeline.prototype.dispose = function () {
  63509. this._disposePostProcesses();
  63510. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63511. _super.prototype.dispose.call(this);
  63512. };
  63513. // Serialize rendering pipeline
  63514. DefaultRenderingPipeline.prototype.serialize = function () {
  63515. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63516. serializationObject.customType = "DefaultRenderingPipeline";
  63517. return serializationObject;
  63518. };
  63519. // Parse serialized pipeline
  63520. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63521. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  63522. };
  63523. __decorate([
  63524. BABYLON.serialize()
  63525. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  63526. __decorate([
  63527. BABYLON.serialize()
  63528. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  63529. __decorate([
  63530. BABYLON.serialize()
  63531. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  63532. __decorate([
  63533. BABYLON.serialize()
  63534. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  63535. __decorate([
  63536. BABYLON.serialize()
  63537. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  63538. __decorate([
  63539. BABYLON.serialize()
  63540. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  63541. __decorate([
  63542. BABYLON.serialize()
  63543. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  63544. __decorate([
  63545. BABYLON.serialize()
  63546. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  63547. return DefaultRenderingPipeline;
  63548. }(BABYLON.PostProcessRenderPipeline));
  63549. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  63550. })(BABYLON || (BABYLON = {}));
  63551. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  63552. var BABYLON;
  63553. (function (BABYLON) {
  63554. /**
  63555. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  63556. */
  63557. var GeometryBufferRenderer = /** @class */ (function () {
  63558. /**
  63559. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  63560. * @param scene The scene the buffer belongs to
  63561. * @param ratio How big is the buffer related to the main canvas.
  63562. */
  63563. function GeometryBufferRenderer(scene, ratio) {
  63564. if (ratio === void 0) { ratio = 1; }
  63565. this._enablePosition = false;
  63566. this._scene = scene;
  63567. this._ratio = ratio;
  63568. // Render target
  63569. this._createRenderTargets();
  63570. }
  63571. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  63572. /**
  63573. * Set the render list (meshes to be rendered) used in the G buffer.
  63574. */
  63575. set: function (meshes) {
  63576. this._multiRenderTarget.renderList = meshes;
  63577. },
  63578. enumerable: true,
  63579. configurable: true
  63580. });
  63581. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  63582. /**
  63583. * Gets wether or not G buffer are supported by the running hardware.
  63584. * This requires draw buffer supports
  63585. */
  63586. get: function () {
  63587. return this._multiRenderTarget.isSupported;
  63588. },
  63589. enumerable: true,
  63590. configurable: true
  63591. });
  63592. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  63593. /**
  63594. * Gets wether or not position are enabled for the G buffer.
  63595. */
  63596. get: function () {
  63597. return this._enablePosition;
  63598. },
  63599. /**
  63600. * Sets wether or not position are enabled for the G buffer.
  63601. */
  63602. set: function (enable) {
  63603. this._enablePosition = enable;
  63604. this.dispose();
  63605. this._createRenderTargets();
  63606. },
  63607. enumerable: true,
  63608. configurable: true
  63609. });
  63610. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  63611. /**
  63612. * Gets the scene associated with the buffer.
  63613. */
  63614. get: function () {
  63615. return this._scene;
  63616. },
  63617. enumerable: true,
  63618. configurable: true
  63619. });
  63620. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  63621. /**
  63622. * Gets the ratio used by the buffer during its creation.
  63623. * How big is the buffer related to the main canvas.
  63624. */
  63625. get: function () {
  63626. return this._ratio;
  63627. },
  63628. enumerable: true,
  63629. configurable: true
  63630. });
  63631. /**
  63632. * Checks wether everything is ready to render a submesh to the G buffer.
  63633. * @param subMesh the submesh to check readiness for
  63634. * @param useInstances is the mesh drawn using instance or not
  63635. * @returns true if ready otherwise false
  63636. */
  63637. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  63638. var material = subMesh.getMaterial();
  63639. if (material && material.disableDepthWrite) {
  63640. return false;
  63641. }
  63642. var defines = [];
  63643. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63644. var mesh = subMesh.getMesh();
  63645. // Alpha test
  63646. if (material && material.needAlphaTesting()) {
  63647. defines.push("#define ALPHATEST");
  63648. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63649. attribs.push(BABYLON.VertexBuffer.UVKind);
  63650. defines.push("#define UV1");
  63651. }
  63652. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63653. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63654. defines.push("#define UV2");
  63655. }
  63656. }
  63657. // Buffers
  63658. if (this._enablePosition) {
  63659. defines.push("#define POSITION");
  63660. }
  63661. // Bones
  63662. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63663. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63664. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63665. if (mesh.numBoneInfluencers > 4) {
  63666. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63667. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63668. }
  63669. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63670. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  63671. }
  63672. else {
  63673. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63674. }
  63675. // Instances
  63676. if (useInstances) {
  63677. defines.push("#define INSTANCES");
  63678. attribs.push("world0");
  63679. attribs.push("world1");
  63680. attribs.push("world2");
  63681. attribs.push("world3");
  63682. }
  63683. // Get correct effect
  63684. var join = defines.join("\n");
  63685. if (this._cachedDefines !== join) {
  63686. this._cachedDefines = join;
  63687. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  63688. }
  63689. return this._effect.isReady();
  63690. };
  63691. /**
  63692. * Gets the current underlying G Buffer.
  63693. * @returns the buffer
  63694. */
  63695. GeometryBufferRenderer.prototype.getGBuffer = function () {
  63696. return this._multiRenderTarget;
  63697. };
  63698. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  63699. /**
  63700. * Gets the number of samples used to render the buffer (anti aliasing).
  63701. */
  63702. get: function () {
  63703. return this._multiRenderTarget.samples;
  63704. },
  63705. /**
  63706. * Sets the number of samples used to render the buffer (anti aliasing).
  63707. */
  63708. set: function (value) {
  63709. this._multiRenderTarget.samples = value;
  63710. },
  63711. enumerable: true,
  63712. configurable: true
  63713. });
  63714. /**
  63715. * Disposes the renderer and frees up associated resources.
  63716. */
  63717. GeometryBufferRenderer.prototype.dispose = function () {
  63718. this.getGBuffer().dispose();
  63719. };
  63720. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  63721. var _this = this;
  63722. var engine = this._scene.getEngine();
  63723. var count = this._enablePosition ? 3 : 2;
  63724. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  63725. if (!this.isSupported) {
  63726. return;
  63727. }
  63728. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63729. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63730. this._multiRenderTarget.refreshRate = 1;
  63731. this._multiRenderTarget.renderParticles = false;
  63732. this._multiRenderTarget.renderList = null;
  63733. // set default depth value to 1.0 (far away)
  63734. this._multiRenderTarget.onClearObservable.add(function (engine) {
  63735. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  63736. });
  63737. // Custom render function
  63738. var renderSubMesh = function (subMesh) {
  63739. var mesh = subMesh.getRenderingMesh();
  63740. var scene = _this._scene;
  63741. var engine = scene.getEngine();
  63742. var material = subMesh.getMaterial();
  63743. if (!material) {
  63744. return;
  63745. }
  63746. // Culling
  63747. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  63748. // Managing instances
  63749. var batch = mesh._getInstancesRenderList(subMesh._id);
  63750. if (batch.mustReturn) {
  63751. return;
  63752. }
  63753. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  63754. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  63755. engine.enableEffect(_this._effect);
  63756. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  63757. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63758. _this._effect.setMatrix("view", scene.getViewMatrix());
  63759. // Alpha test
  63760. if (material && material.needAlphaTesting()) {
  63761. var alphaTexture = material.getAlphaTestTexture();
  63762. if (alphaTexture) {
  63763. _this._effect.setTexture("diffuseSampler", alphaTexture);
  63764. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63765. }
  63766. }
  63767. // Bones
  63768. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63769. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63770. }
  63771. // Draw
  63772. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  63773. }
  63774. };
  63775. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63776. var index;
  63777. if (depthOnlySubMeshes.length) {
  63778. engine.setColorWrite(false);
  63779. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63780. renderSubMesh(depthOnlySubMeshes.data[index]);
  63781. }
  63782. engine.setColorWrite(true);
  63783. }
  63784. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63785. renderSubMesh(opaqueSubMeshes.data[index]);
  63786. }
  63787. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63788. renderSubMesh(alphaTestSubMeshes.data[index]);
  63789. }
  63790. };
  63791. };
  63792. return GeometryBufferRenderer;
  63793. }());
  63794. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  63795. })(BABYLON || (BABYLON = {}));
  63796. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  63797. var BABYLON;
  63798. (function (BABYLON) {
  63799. var RefractionPostProcess = /** @class */ (function (_super) {
  63800. __extends(RefractionPostProcess, _super);
  63801. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  63802. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  63803. _this.color = color;
  63804. _this.depth = depth;
  63805. _this.colorLevel = colorLevel;
  63806. _this.onActivateObservable.add(function (cam) {
  63807. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  63808. });
  63809. _this.onApplyObservable.add(function (effect) {
  63810. effect.setColor3("baseColor", _this.color);
  63811. effect.setFloat("depth", _this.depth);
  63812. effect.setFloat("colorLevel", _this.colorLevel);
  63813. effect.setTexture("refractionSampler", _this._refRexture);
  63814. });
  63815. return _this;
  63816. }
  63817. // Methods
  63818. RefractionPostProcess.prototype.dispose = function (camera) {
  63819. if (this._refRexture) {
  63820. this._refRexture.dispose();
  63821. }
  63822. _super.prototype.dispose.call(this, camera);
  63823. };
  63824. return RefractionPostProcess;
  63825. }(BABYLON.PostProcess));
  63826. BABYLON.RefractionPostProcess = RefractionPostProcess;
  63827. })(BABYLON || (BABYLON = {}));
  63828. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  63829. var BABYLON;
  63830. (function (BABYLON) {
  63831. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  63832. __extends(BlackAndWhitePostProcess, _super);
  63833. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  63834. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  63835. _this.degree = 1;
  63836. _this.onApplyObservable.add(function (effect) {
  63837. effect.setFloat("degree", _this.degree);
  63838. });
  63839. return _this;
  63840. }
  63841. return BlackAndWhitePostProcess;
  63842. }(BABYLON.PostProcess));
  63843. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  63844. })(BABYLON || (BABYLON = {}));
  63845. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  63846. var BABYLON;
  63847. (function (BABYLON) {
  63848. var ConvolutionPostProcess = /** @class */ (function (_super) {
  63849. __extends(ConvolutionPostProcess, _super);
  63850. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  63851. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  63852. _this.kernel = kernel;
  63853. _this.onApply = function (effect) {
  63854. effect.setFloat2("screenSize", _this.width, _this.height);
  63855. effect.setArray("kernel", _this.kernel);
  63856. };
  63857. return _this;
  63858. }
  63859. // Statics
  63860. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  63861. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  63862. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  63863. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  63864. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  63865. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  63866. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  63867. return ConvolutionPostProcess;
  63868. }(BABYLON.PostProcess));
  63869. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  63870. })(BABYLON || (BABYLON = {}));
  63871. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  63872. var BABYLON;
  63873. (function (BABYLON) {
  63874. var FilterPostProcess = /** @class */ (function (_super) {
  63875. __extends(FilterPostProcess, _super);
  63876. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  63877. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  63878. _this.kernelMatrix = kernelMatrix;
  63879. _this.onApply = function (effect) {
  63880. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  63881. };
  63882. return _this;
  63883. }
  63884. return FilterPostProcess;
  63885. }(BABYLON.PostProcess));
  63886. BABYLON.FilterPostProcess = FilterPostProcess;
  63887. })(BABYLON || (BABYLON = {}));
  63888. //# sourceMappingURL=babylon.filterPostProcess.js.map
  63889. var BABYLON;
  63890. (function (BABYLON) {
  63891. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  63892. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  63893. __extends(VolumetricLightScatteringPostProcess, _super);
  63894. /**
  63895. * @constructor
  63896. * @param {string} name - The post-process name
  63897. * @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)
  63898. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  63899. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  63900. * @param {number} samples - The post-process quality, default 100
  63901. * @param {number} samplingMode - The post-process filtering mode
  63902. * @param {BABYLON.Engine} engine - The babylon engine
  63903. * @param {boolean} reusable - If the post-process is reusable
  63904. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  63905. */
  63906. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  63907. if (samples === void 0) { samples = 100; }
  63908. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63909. 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;
  63910. _this._screenCoordinates = BABYLON.Vector2.Zero();
  63911. /**
  63912. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  63913. * @type {Vector3}
  63914. */
  63915. _this.customMeshPosition = BABYLON.Vector3.Zero();
  63916. /**
  63917. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  63918. * @type {boolean}
  63919. */
  63920. _this.useCustomMeshPosition = false;
  63921. /**
  63922. * If the post-process should inverse the light scattering direction
  63923. * @type {boolean}
  63924. */
  63925. _this.invert = true;
  63926. /**
  63927. * Array containing the excluded meshes not rendered in the internal pass
  63928. */
  63929. _this.excludedMeshes = new Array();
  63930. /**
  63931. * Controls the overall intensity of the post-process
  63932. * @type {number}
  63933. */
  63934. _this.exposure = 0.3;
  63935. /**
  63936. * Dissipates each sample's contribution in range [0, 1]
  63937. * @type {number}
  63938. */
  63939. _this.decay = 0.96815;
  63940. /**
  63941. * Controls the overall intensity of each sample
  63942. * @type {number}
  63943. */
  63944. _this.weight = 0.58767;
  63945. /**
  63946. * Controls the density of each sample
  63947. * @type {number}
  63948. */
  63949. _this.density = 0.926;
  63950. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  63951. engine = scene.getEngine();
  63952. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  63953. // Configure mesh
  63954. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  63955. // Configure
  63956. _this._createPass(scene, ratio.passRatio || ratio);
  63957. _this.onActivate = function (camera) {
  63958. if (!_this.isSupported) {
  63959. _this.dispose(camera);
  63960. }
  63961. _this.onActivate = null;
  63962. };
  63963. _this.onApplyObservable.add(function (effect) {
  63964. _this._updateMeshScreenCoordinates(scene);
  63965. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  63966. effect.setFloat("exposure", _this.exposure);
  63967. effect.setFloat("decay", _this.decay);
  63968. effect.setFloat("weight", _this.weight);
  63969. effect.setFloat("density", _this.density);
  63970. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  63971. });
  63972. return _this;
  63973. }
  63974. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  63975. get: function () {
  63976. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63977. return false;
  63978. },
  63979. set: function (useDiffuseColor) {
  63980. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63981. },
  63982. enumerable: true,
  63983. configurable: true
  63984. });
  63985. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  63986. return "VolumetricLightScatteringPostProcess";
  63987. };
  63988. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  63989. var mesh = subMesh.getMesh();
  63990. // Render this.mesh as default
  63991. if (mesh === this.mesh && mesh.material) {
  63992. return mesh.material.isReady(mesh);
  63993. }
  63994. var defines = [];
  63995. var attribs = [BABYLON.VertexBuffer.PositionKind];
  63996. var material = subMesh.getMaterial();
  63997. // Alpha test
  63998. if (material) {
  63999. if (material.needAlphaTesting()) {
  64000. defines.push("#define ALPHATEST");
  64001. }
  64002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64003. attribs.push(BABYLON.VertexBuffer.UVKind);
  64004. defines.push("#define UV1");
  64005. }
  64006. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64007. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64008. defines.push("#define UV2");
  64009. }
  64010. }
  64011. // Bones
  64012. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64013. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64014. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64015. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64016. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  64017. }
  64018. else {
  64019. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64020. }
  64021. // Instances
  64022. if (useInstances) {
  64023. defines.push("#define INSTANCES");
  64024. attribs.push("world0");
  64025. attribs.push("world1");
  64026. attribs.push("world2");
  64027. attribs.push("world3");
  64028. }
  64029. // Get correct effect
  64030. var join = defines.join("\n");
  64031. if (this._cachedDefines !== join) {
  64032. this._cachedDefines = join;
  64033. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  64034. }
  64035. return this._volumetricLightScatteringPass.isReady();
  64036. };
  64037. /**
  64038. * Sets the new light position for light scattering effect
  64039. * @param {BABYLON.Vector3} The new custom light position
  64040. */
  64041. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  64042. this.customMeshPosition = position;
  64043. };
  64044. /**
  64045. * Returns the light position for light scattering effect
  64046. * @return {BABYLON.Vector3} The custom light position
  64047. */
  64048. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  64049. return this.customMeshPosition;
  64050. };
  64051. /**
  64052. * Disposes the internal assets and detaches the post-process from the camera
  64053. */
  64054. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  64055. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  64056. if (rttIndex !== -1) {
  64057. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  64058. }
  64059. this._volumetricLightScatteringRTT.dispose();
  64060. _super.prototype.dispose.call(this, camera);
  64061. };
  64062. /**
  64063. * Returns the render target texture used by the post-process
  64064. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  64065. */
  64066. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  64067. return this._volumetricLightScatteringRTT;
  64068. };
  64069. // Private methods
  64070. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  64071. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  64072. return true;
  64073. }
  64074. return false;
  64075. };
  64076. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  64077. var _this = this;
  64078. var engine = scene.getEngine();
  64079. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64080. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64081. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64082. this._volumetricLightScatteringRTT.renderList = null;
  64083. this._volumetricLightScatteringRTT.renderParticles = false;
  64084. var camera = this.getCamera();
  64085. if (camera) {
  64086. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64087. }
  64088. else {
  64089. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64090. }
  64091. // Custom render function for submeshes
  64092. var renderSubMesh = function (subMesh) {
  64093. var mesh = subMesh.getRenderingMesh();
  64094. if (_this._meshExcluded(mesh)) {
  64095. return;
  64096. }
  64097. var material = subMesh.getMaterial();
  64098. if (!material) {
  64099. return;
  64100. }
  64101. var scene = mesh.getScene();
  64102. var engine = scene.getEngine();
  64103. // Culling
  64104. engine.setState(material.backFaceCulling);
  64105. // Managing instances
  64106. var batch = mesh._getInstancesRenderList(subMesh._id);
  64107. if (batch.mustReturn) {
  64108. return;
  64109. }
  64110. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64111. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  64112. var effect = _this._volumetricLightScatteringPass;
  64113. if (mesh === _this.mesh) {
  64114. if (subMesh.effect) {
  64115. effect = subMesh.effect;
  64116. }
  64117. else {
  64118. effect = material.getEffect();
  64119. }
  64120. }
  64121. engine.enableEffect(effect);
  64122. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  64123. if (mesh === _this.mesh) {
  64124. material.bind(mesh.getWorldMatrix(), mesh);
  64125. }
  64126. else {
  64127. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  64128. // Alpha test
  64129. if (material && material.needAlphaTesting()) {
  64130. var alphaTexture = material.getAlphaTestTexture();
  64131. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  64132. if (alphaTexture) {
  64133. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64134. }
  64135. }
  64136. // Bones
  64137. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64138. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64139. }
  64140. }
  64141. // Draw
  64142. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  64143. }
  64144. };
  64145. // Render target texture callbacks
  64146. var savedSceneClearColor;
  64147. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  64148. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  64149. savedSceneClearColor = scene.clearColor;
  64150. scene.clearColor = sceneClearColor;
  64151. });
  64152. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  64153. scene.clearColor = savedSceneClearColor;
  64154. });
  64155. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64156. var engine = scene.getEngine();
  64157. var index;
  64158. if (depthOnlySubMeshes.length) {
  64159. engine.setColorWrite(false);
  64160. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64161. renderSubMesh(depthOnlySubMeshes.data[index]);
  64162. }
  64163. engine.setColorWrite(true);
  64164. }
  64165. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64166. renderSubMesh(opaqueSubMeshes.data[index]);
  64167. }
  64168. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64169. renderSubMesh(alphaTestSubMeshes.data[index]);
  64170. }
  64171. if (transparentSubMeshes.length) {
  64172. // Sort sub meshes
  64173. for (index = 0; index < transparentSubMeshes.length; index++) {
  64174. var submesh = transparentSubMeshes.data[index];
  64175. var boundingInfo = submesh.getBoundingInfo();
  64176. if (boundingInfo && scene.activeCamera) {
  64177. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64178. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64179. }
  64180. }
  64181. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64182. sortedArray.sort(function (a, b) {
  64183. // Alpha index first
  64184. if (a._alphaIndex > b._alphaIndex) {
  64185. return 1;
  64186. }
  64187. if (a._alphaIndex < b._alphaIndex) {
  64188. return -1;
  64189. }
  64190. // Then distance to camera
  64191. if (a._distanceToCamera < b._distanceToCamera) {
  64192. return 1;
  64193. }
  64194. if (a._distanceToCamera > b._distanceToCamera) {
  64195. return -1;
  64196. }
  64197. return 0;
  64198. });
  64199. // Render sub meshes
  64200. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64201. for (index = 0; index < sortedArray.length; index++) {
  64202. renderSubMesh(sortedArray[index]);
  64203. }
  64204. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64205. }
  64206. };
  64207. };
  64208. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64209. var transform = scene.getTransformMatrix();
  64210. var meshPosition;
  64211. if (this.useCustomMeshPosition) {
  64212. meshPosition = this.customMeshPosition;
  64213. }
  64214. else if (this.attachedNode) {
  64215. meshPosition = this.attachedNode.position;
  64216. }
  64217. else {
  64218. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64219. }
  64220. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64221. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64222. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64223. if (this.invert)
  64224. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64225. };
  64226. // Static methods
  64227. /**
  64228. * Creates a default mesh for the Volumeric Light Scattering post-process
  64229. * @param {string} The mesh name
  64230. * @param {BABYLON.Scene} The scene where to create the mesh
  64231. * @return {BABYLON.Mesh} the default mesh
  64232. */
  64233. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64234. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64235. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64236. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64237. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64238. mesh.material = material;
  64239. return mesh;
  64240. };
  64241. __decorate([
  64242. BABYLON.serializeAsVector3()
  64243. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64244. __decorate([
  64245. BABYLON.serialize()
  64246. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64247. __decorate([
  64248. BABYLON.serialize()
  64249. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64250. __decorate([
  64251. BABYLON.serializeAsMeshReference()
  64252. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64253. __decorate([
  64254. BABYLON.serialize()
  64255. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64256. __decorate([
  64257. BABYLON.serialize()
  64258. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64259. __decorate([
  64260. BABYLON.serialize()
  64261. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64262. __decorate([
  64263. BABYLON.serialize()
  64264. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64265. __decorate([
  64266. BABYLON.serialize()
  64267. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64268. return VolumetricLightScatteringPostProcess;
  64269. }(BABYLON.PostProcess));
  64270. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64271. })(BABYLON || (BABYLON = {}));
  64272. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64273. //
  64274. // This post-process allows the modification of rendered colors by using
  64275. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64276. //
  64277. // The object needs to be provided an url to a texture containing the color
  64278. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64279. // Use an image editing software to tweak the LUT to match your needs.
  64280. //
  64281. // For an example of a color LUT, see here:
  64282. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64283. // For explanations on color grading, see here:
  64284. // http://udn.epicgames.com/Three/ColorGrading.html
  64285. //
  64286. var BABYLON;
  64287. (function (BABYLON) {
  64288. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64289. __extends(ColorCorrectionPostProcess, _super);
  64290. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64291. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64292. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64293. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64294. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64295. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64296. _this.onApply = function (effect) {
  64297. effect.setTexture("colorTable", _this._colorTableTexture);
  64298. };
  64299. return _this;
  64300. }
  64301. return ColorCorrectionPostProcess;
  64302. }(BABYLON.PostProcess));
  64303. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64304. })(BABYLON || (BABYLON = {}));
  64305. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64306. var BABYLON;
  64307. (function (BABYLON) {
  64308. var TonemappingOperator;
  64309. (function (TonemappingOperator) {
  64310. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64311. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64312. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64313. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64314. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64315. ;
  64316. var TonemapPostProcess = /** @class */ (function (_super) {
  64317. __extends(TonemapPostProcess, _super);
  64318. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64320. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64321. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64322. _this._operator = _operator;
  64323. _this.exposureAdjustment = exposureAdjustment;
  64324. var defines = "#define ";
  64325. if (_this._operator === TonemappingOperator.Hable)
  64326. defines += "HABLE_TONEMAPPING";
  64327. else if (_this._operator === TonemappingOperator.Reinhard)
  64328. defines += "REINHARD_TONEMAPPING";
  64329. else if (_this._operator === TonemappingOperator.HejiDawson)
  64330. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64331. else if (_this._operator === TonemappingOperator.Photographic)
  64332. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64333. //sadly a second call to create the effect.
  64334. _this.updateEffect(defines);
  64335. _this.onApply = function (effect) {
  64336. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64337. };
  64338. return _this;
  64339. }
  64340. return TonemapPostProcess;
  64341. }(BABYLON.PostProcess));
  64342. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64343. })(BABYLON || (BABYLON = {}));
  64344. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64345. var BABYLON;
  64346. (function (BABYLON) {
  64347. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64348. __extends(DisplayPassPostProcess, _super);
  64349. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64350. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64351. }
  64352. return DisplayPassPostProcess;
  64353. }(BABYLON.PostProcess));
  64354. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64355. })(BABYLON || (BABYLON = {}));
  64356. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64357. var BABYLON;
  64358. (function (BABYLON) {
  64359. var HighlightsPostProcess = /** @class */ (function (_super) {
  64360. __extends(HighlightsPostProcess, _super);
  64361. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64362. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64363. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64364. }
  64365. return HighlightsPostProcess;
  64366. }(BABYLON.PostProcess));
  64367. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64368. })(BABYLON || (BABYLON = {}));
  64369. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64370. var BABYLON;
  64371. (function (BABYLON) {
  64372. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64373. __extends(ImageProcessingPostProcess, _super);
  64374. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64375. if (camera === void 0) { camera = null; }
  64376. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64377. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64378. _this._fromLinearSpace = true;
  64379. /**
  64380. * Defines cache preventing GC.
  64381. */
  64382. _this._defines = {
  64383. IMAGEPROCESSING: false,
  64384. VIGNETTE: false,
  64385. VIGNETTEBLENDMODEMULTIPLY: false,
  64386. VIGNETTEBLENDMODEOPAQUE: false,
  64387. TONEMAPPING: false,
  64388. CONTRAST: false,
  64389. COLORCURVES: false,
  64390. COLORGRADING: false,
  64391. COLORGRADING3D: false,
  64392. FROMLINEARSPACE: false,
  64393. SAMPLER3DGREENDEPTH: false,
  64394. SAMPLER3DBGRMAP: false,
  64395. IMAGEPROCESSINGPOSTPROCESS: false,
  64396. EXPOSURE: false,
  64397. };
  64398. // Setup the configuration as forced by the constructor. This would then not force the
  64399. // scene materials output in linear space and let untouched the default forward pass.
  64400. if (imageProcessingConfiguration) {
  64401. imageProcessingConfiguration.applyByPostProcess = true;
  64402. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64403. // This will cause the shader to be compiled
  64404. _this.fromLinearSpace = false;
  64405. }
  64406. else {
  64407. _this._attachImageProcessingConfiguration(null, true);
  64408. _this.imageProcessingConfiguration.applyByPostProcess = true;
  64409. }
  64410. _this.onApply = function (effect) {
  64411. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  64412. };
  64413. return _this;
  64414. }
  64415. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  64416. /**
  64417. * Gets the image processing configuration used either in this material.
  64418. */
  64419. get: function () {
  64420. return this._imageProcessingConfiguration;
  64421. },
  64422. /**
  64423. * Sets the Default image processing configuration used either in the this material.
  64424. *
  64425. * If sets to null, the scene one is in use.
  64426. */
  64427. set: function (value) {
  64428. this._attachImageProcessingConfiguration(value);
  64429. },
  64430. enumerable: true,
  64431. configurable: true
  64432. });
  64433. /**
  64434. * Attaches a new image processing configuration to the PBR Material.
  64435. * @param configuration
  64436. */
  64437. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  64438. var _this = this;
  64439. if (doNotBuild === void 0) { doNotBuild = false; }
  64440. if (configuration === this._imageProcessingConfiguration) {
  64441. return;
  64442. }
  64443. // Detaches observer.
  64444. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64445. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64446. }
  64447. // Pick the scene configuration if needed.
  64448. if (!configuration) {
  64449. var scene = null;
  64450. var engine = this.getEngine();
  64451. var camera = this.getCamera();
  64452. if (camera) {
  64453. scene = camera.getScene();
  64454. }
  64455. else if (engine && engine.scenes) {
  64456. var scenes = engine.scenes;
  64457. scene = scenes[scenes.length - 1];
  64458. }
  64459. else {
  64460. scene = BABYLON.Engine.LastCreatedScene;
  64461. }
  64462. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  64463. }
  64464. else {
  64465. this._imageProcessingConfiguration = configuration;
  64466. }
  64467. // Attaches observer.
  64468. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  64469. _this._updateParameters();
  64470. });
  64471. // Ensure the effect will be rebuilt.
  64472. if (!doNotBuild) {
  64473. this._updateParameters();
  64474. }
  64475. };
  64476. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  64477. /**
  64478. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64479. */
  64480. get: function () {
  64481. return this.imageProcessingConfiguration.colorCurves;
  64482. },
  64483. /**
  64484. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64485. */
  64486. set: function (value) {
  64487. this.imageProcessingConfiguration.colorCurves = value;
  64488. },
  64489. enumerable: true,
  64490. configurable: true
  64491. });
  64492. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  64493. /**
  64494. * Gets wether the color curves effect is enabled.
  64495. */
  64496. get: function () {
  64497. return this.imageProcessingConfiguration.colorCurvesEnabled;
  64498. },
  64499. /**
  64500. * Sets wether the color curves effect is enabled.
  64501. */
  64502. set: function (value) {
  64503. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  64504. },
  64505. enumerable: true,
  64506. configurable: true
  64507. });
  64508. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  64509. /**
  64510. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64511. */
  64512. get: function () {
  64513. return this.imageProcessingConfiguration.colorGradingTexture;
  64514. },
  64515. /**
  64516. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64517. */
  64518. set: function (value) {
  64519. this.imageProcessingConfiguration.colorGradingTexture = value;
  64520. },
  64521. enumerable: true,
  64522. configurable: true
  64523. });
  64524. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  64525. /**
  64526. * Gets wether the color grading effect is enabled.
  64527. */
  64528. get: function () {
  64529. return this.imageProcessingConfiguration.colorGradingEnabled;
  64530. },
  64531. /**
  64532. * Gets wether the color grading effect is enabled.
  64533. */
  64534. set: function (value) {
  64535. this.imageProcessingConfiguration.colorGradingEnabled = value;
  64536. },
  64537. enumerable: true,
  64538. configurable: true
  64539. });
  64540. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  64541. /**
  64542. * Gets exposure used in the effect.
  64543. */
  64544. get: function () {
  64545. return this.imageProcessingConfiguration.exposure;
  64546. },
  64547. /**
  64548. * Sets exposure used in the effect.
  64549. */
  64550. set: function (value) {
  64551. this.imageProcessingConfiguration.exposure = value;
  64552. },
  64553. enumerable: true,
  64554. configurable: true
  64555. });
  64556. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  64557. /**
  64558. * Gets wether tonemapping is enabled or not.
  64559. */
  64560. get: function () {
  64561. return this._imageProcessingConfiguration.toneMappingEnabled;
  64562. },
  64563. /**
  64564. * Sets wether tonemapping is enabled or not
  64565. */
  64566. set: function (value) {
  64567. this._imageProcessingConfiguration.toneMappingEnabled = value;
  64568. },
  64569. enumerable: true,
  64570. configurable: true
  64571. });
  64572. ;
  64573. ;
  64574. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  64575. /**
  64576. * Gets contrast used in the effect.
  64577. */
  64578. get: function () {
  64579. return this.imageProcessingConfiguration.contrast;
  64580. },
  64581. /**
  64582. * Sets contrast used in the effect.
  64583. */
  64584. set: function (value) {
  64585. this.imageProcessingConfiguration.contrast = value;
  64586. },
  64587. enumerable: true,
  64588. configurable: true
  64589. });
  64590. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  64591. /**
  64592. * Gets Vignette stretch size.
  64593. */
  64594. get: function () {
  64595. return this.imageProcessingConfiguration.vignetteStretch;
  64596. },
  64597. /**
  64598. * Sets Vignette stretch size.
  64599. */
  64600. set: function (value) {
  64601. this.imageProcessingConfiguration.vignetteStretch = value;
  64602. },
  64603. enumerable: true,
  64604. configurable: true
  64605. });
  64606. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  64607. /**
  64608. * Gets Vignette centre X Offset.
  64609. */
  64610. get: function () {
  64611. return this.imageProcessingConfiguration.vignetteCentreX;
  64612. },
  64613. /**
  64614. * Sets Vignette centre X Offset.
  64615. */
  64616. set: function (value) {
  64617. this.imageProcessingConfiguration.vignetteCentreX = value;
  64618. },
  64619. enumerable: true,
  64620. configurable: true
  64621. });
  64622. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  64623. /**
  64624. * Gets Vignette centre Y Offset.
  64625. */
  64626. get: function () {
  64627. return this.imageProcessingConfiguration.vignetteCentreY;
  64628. },
  64629. /**
  64630. * Sets Vignette centre Y Offset.
  64631. */
  64632. set: function (value) {
  64633. this.imageProcessingConfiguration.vignetteCentreY = value;
  64634. },
  64635. enumerable: true,
  64636. configurable: true
  64637. });
  64638. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  64639. /**
  64640. * Gets Vignette weight or intensity of the vignette effect.
  64641. */
  64642. get: function () {
  64643. return this.imageProcessingConfiguration.vignetteWeight;
  64644. },
  64645. /**
  64646. * Sets Vignette weight or intensity of the vignette effect.
  64647. */
  64648. set: function (value) {
  64649. this.imageProcessingConfiguration.vignetteWeight = value;
  64650. },
  64651. enumerable: true,
  64652. configurable: true
  64653. });
  64654. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  64655. /**
  64656. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64657. * if vignetteEnabled is set to true.
  64658. */
  64659. get: function () {
  64660. return this.imageProcessingConfiguration.vignetteColor;
  64661. },
  64662. /**
  64663. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64664. * if vignetteEnabled is set to true.
  64665. */
  64666. set: function (value) {
  64667. this.imageProcessingConfiguration.vignetteColor = value;
  64668. },
  64669. enumerable: true,
  64670. configurable: true
  64671. });
  64672. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  64673. /**
  64674. * Gets Camera field of view used by the Vignette effect.
  64675. */
  64676. get: function () {
  64677. return this.imageProcessingConfiguration.vignetteCameraFov;
  64678. },
  64679. /**
  64680. * Sets Camera field of view used by the Vignette effect.
  64681. */
  64682. set: function (value) {
  64683. this.imageProcessingConfiguration.vignetteCameraFov = value;
  64684. },
  64685. enumerable: true,
  64686. configurable: true
  64687. });
  64688. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  64689. /**
  64690. * Gets the vignette blend mode allowing different kind of effect.
  64691. */
  64692. get: function () {
  64693. return this.imageProcessingConfiguration.vignetteBlendMode;
  64694. },
  64695. /**
  64696. * Sets the vignette blend mode allowing different kind of effect.
  64697. */
  64698. set: function (value) {
  64699. this.imageProcessingConfiguration.vignetteBlendMode = value;
  64700. },
  64701. enumerable: true,
  64702. configurable: true
  64703. });
  64704. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  64705. /**
  64706. * Gets wether the vignette effect is enabled.
  64707. */
  64708. get: function () {
  64709. return this.imageProcessingConfiguration.vignetteEnabled;
  64710. },
  64711. /**
  64712. * Sets wether the vignette effect is enabled.
  64713. */
  64714. set: function (value) {
  64715. this.imageProcessingConfiguration.vignetteEnabled = value;
  64716. },
  64717. enumerable: true,
  64718. configurable: true
  64719. });
  64720. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  64721. /**
  64722. * Gets wether the input of the processing is in Gamma or Linear Space.
  64723. */
  64724. get: function () {
  64725. return this._fromLinearSpace;
  64726. },
  64727. /**
  64728. * Sets wether the input of the processing is in Gamma or Linear Space.
  64729. */
  64730. set: function (value) {
  64731. if (this._fromLinearSpace === value) {
  64732. return;
  64733. }
  64734. this._fromLinearSpace = value;
  64735. this._updateParameters();
  64736. },
  64737. enumerable: true,
  64738. configurable: true
  64739. });
  64740. ImageProcessingPostProcess.prototype.getClassName = function () {
  64741. return "ImageProcessingPostProcess";
  64742. };
  64743. ImageProcessingPostProcess.prototype._updateParameters = function () {
  64744. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  64745. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  64746. var defines = "";
  64747. for (var define in this._defines) {
  64748. if (this._defines[define]) {
  64749. defines += "#define " + define + ";\r\n";
  64750. }
  64751. }
  64752. var samplers = ["textureSampler"];
  64753. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  64754. var uniforms = ["scale"];
  64755. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  64756. this.updateEffect(defines, uniforms, samplers);
  64757. };
  64758. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  64759. _super.prototype.dispose.call(this, camera);
  64760. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64761. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64762. }
  64763. this.imageProcessingConfiguration.applyByPostProcess = false;
  64764. };
  64765. __decorate([
  64766. BABYLON.serialize()
  64767. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  64768. return ImageProcessingPostProcess;
  64769. }(BABYLON.PostProcess));
  64770. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  64771. })(BABYLON || (BABYLON = {}));
  64772. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  64773. var BABYLON;
  64774. (function (BABYLON) {
  64775. var BlurPostProcess = /** @class */ (function (_super) {
  64776. __extends(BlurPostProcess, _super);
  64777. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  64778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64779. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64780. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  64781. _this.direction = direction;
  64782. _this._packedFloat = false;
  64783. _this.onApplyObservable.add(function (effect) {
  64784. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  64785. });
  64786. _this.kernel = kernel;
  64787. return _this;
  64788. }
  64789. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  64790. /**
  64791. * Gets the length in pixels of the blur sample region
  64792. */
  64793. get: function () {
  64794. return this._idealKernel;
  64795. },
  64796. /**
  64797. * Sets the length in pixels of the blur sample region
  64798. */
  64799. set: function (v) {
  64800. if (this._idealKernel === v) {
  64801. return;
  64802. }
  64803. v = Math.max(v, 1);
  64804. this._idealKernel = v;
  64805. this._kernel = this._nearestBestKernel(v);
  64806. this._updateParameters();
  64807. },
  64808. enumerable: true,
  64809. configurable: true
  64810. });
  64811. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  64812. /**
  64813. * Gets wether or not the blur is unpacking/repacking floats
  64814. */
  64815. get: function () {
  64816. return this._packedFloat;
  64817. },
  64818. /**
  64819. * Sets wether or not the blur needs to unpack/repack floats
  64820. */
  64821. set: function (v) {
  64822. if (this._packedFloat === v) {
  64823. return;
  64824. }
  64825. this._packedFloat = v;
  64826. this._updateParameters();
  64827. },
  64828. enumerable: true,
  64829. configurable: true
  64830. });
  64831. BlurPostProcess.prototype._updateParameters = function () {
  64832. // Generate sampling offsets and weights
  64833. var N = this._kernel;
  64834. var centerIndex = (N - 1) / 2;
  64835. // Generate Gaussian sampling weights over kernel
  64836. var offsets = [];
  64837. var weights = [];
  64838. var totalWeight = 0;
  64839. for (var i = 0; i < N; i++) {
  64840. var u = i / (N - 1);
  64841. var w = this._gaussianWeight(u * 2.0 - 1);
  64842. offsets[i] = (i - centerIndex);
  64843. weights[i] = w;
  64844. totalWeight += w;
  64845. }
  64846. // Normalize weights
  64847. for (var i = 0; i < weights.length; i++) {
  64848. weights[i] /= totalWeight;
  64849. }
  64850. // Optimize: combine samples to take advantage of hardware linear sampling
  64851. // Walk from left to center, combining pairs (symmetrically)
  64852. var linearSamplingWeights = [];
  64853. var linearSamplingOffsets = [];
  64854. var linearSamplingMap = [];
  64855. for (var i = 0; i <= centerIndex; i += 2) {
  64856. var j = Math.min(i + 1, Math.floor(centerIndex));
  64857. var singleCenterSample = i === j;
  64858. if (singleCenterSample) {
  64859. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64860. }
  64861. else {
  64862. var sharedCell = j === centerIndex;
  64863. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  64864. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  64865. if (offsetLinear === 0) {
  64866. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64867. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  64868. }
  64869. else {
  64870. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  64871. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  64872. }
  64873. }
  64874. }
  64875. for (var i = 0; i < linearSamplingMap.length; i++) {
  64876. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  64877. linearSamplingWeights[i] = linearSamplingMap[i].w;
  64878. }
  64879. // Replace with optimized
  64880. offsets = linearSamplingOffsets;
  64881. weights = linearSamplingWeights;
  64882. // Generate shaders
  64883. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  64884. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  64885. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  64886. var defines = "";
  64887. for (var i = 0; i < varyingCount; i++) {
  64888. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  64889. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  64890. }
  64891. var depCount = 0;
  64892. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  64893. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  64894. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  64895. depCount++;
  64896. }
  64897. if (this.packedFloat) {
  64898. defines += "#define PACKEDFLOAT 1";
  64899. }
  64900. this.updateEffect(defines, null, null, {
  64901. varyingCount: varyingCount,
  64902. depCount: depCount
  64903. });
  64904. };
  64905. /**
  64906. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  64907. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  64908. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  64909. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  64910. * The gaps between physical kernels are compensated for in the weighting of the samples
  64911. * @param idealKernel Ideal blur kernel.
  64912. * @return Nearest best kernel.
  64913. */
  64914. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  64915. var v = Math.round(idealKernel);
  64916. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  64917. var k = _a[_i];
  64918. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  64919. return Math.max(k, 3);
  64920. }
  64921. }
  64922. return Math.max(v, 3);
  64923. };
  64924. /**
  64925. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  64926. * @param x The point on the Gaussian distribution to sample.
  64927. * @return the value of the Gaussian function at x.
  64928. */
  64929. BlurPostProcess.prototype._gaussianWeight = function (x) {
  64930. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  64931. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  64932. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  64933. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  64934. // truncated at around 1.3% of peak strength.
  64935. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  64936. var sigma = (1 / 3);
  64937. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  64938. var exponent = -((x * x) / (2.0 * sigma * sigma));
  64939. var weight = (1.0 / denominator) * Math.exp(exponent);
  64940. return weight;
  64941. };
  64942. /**
  64943. * Generates a string that can be used as a floating point number in GLSL.
  64944. * @param x Value to print.
  64945. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  64946. * @return GLSL float string.
  64947. */
  64948. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  64949. if (decimalFigures === void 0) { decimalFigures = 8; }
  64950. return x.toFixed(decimalFigures).replace(/0+$/, '');
  64951. };
  64952. return BlurPostProcess;
  64953. }(BABYLON.PostProcess));
  64954. BABYLON.BlurPostProcess = BlurPostProcess;
  64955. })(BABYLON || (BABYLON = {}));
  64956. //# sourceMappingURL=babylon.blurPostProcess.js.map
  64957. var BABYLON;
  64958. (function (BABYLON) {
  64959. var Bone = /** @class */ (function (_super) {
  64960. __extends(Bone, _super);
  64961. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  64962. if (parentBone === void 0) { parentBone = null; }
  64963. if (localMatrix === void 0) { localMatrix = null; }
  64964. if (restPose === void 0) { restPose = null; }
  64965. if (baseMatrix === void 0) { baseMatrix = null; }
  64966. if (index === void 0) { index = null; }
  64967. var _this = _super.call(this, name, skeleton.getScene()) || this;
  64968. _this.name = name;
  64969. _this.children = new Array();
  64970. _this.animations = new Array();
  64971. // Set this value to map this bone to a different index in the transform matrices.
  64972. // Set this value to -1 to exclude the bone from the transform matrices.
  64973. _this._index = null;
  64974. _this._worldTransform = new BABYLON.Matrix();
  64975. _this._absoluteTransform = new BABYLON.Matrix();
  64976. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  64977. _this._scaleMatrix = BABYLON.Matrix.Identity();
  64978. _this._scaleVector = BABYLON.Vector3.One();
  64979. _this._negateScaleChildren = BABYLON.Vector3.One();
  64980. _this._scalingDeterminant = 1;
  64981. _this._skeleton = skeleton;
  64982. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  64983. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  64984. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  64985. _this._index = index;
  64986. skeleton.bones.push(_this);
  64987. _this.setParent(parentBone, false);
  64988. _this._updateDifferenceMatrix();
  64989. return _this;
  64990. }
  64991. Object.defineProperty(Bone.prototype, "_matrix", {
  64992. get: function () {
  64993. return this._localMatrix;
  64994. },
  64995. set: function (val) {
  64996. if (this._localMatrix) {
  64997. this._localMatrix.copyFrom(val);
  64998. }
  64999. else {
  65000. this._localMatrix = val;
  65001. }
  65002. },
  65003. enumerable: true,
  65004. configurable: true
  65005. });
  65006. // Members
  65007. Bone.prototype.getSkeleton = function () {
  65008. return this._skeleton;
  65009. };
  65010. Bone.prototype.getParent = function () {
  65011. return this._parent;
  65012. };
  65013. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  65014. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65015. if (this._parent === parent) {
  65016. return;
  65017. }
  65018. if (this._parent) {
  65019. var index = this._parent.children.indexOf(this);
  65020. if (index !== -1) {
  65021. this._parent.children.splice(index, 1);
  65022. }
  65023. }
  65024. this._parent = parent;
  65025. if (this._parent) {
  65026. this._parent.children.push(this);
  65027. }
  65028. if (updateDifferenceMatrix) {
  65029. this._updateDifferenceMatrix();
  65030. }
  65031. };
  65032. Bone.prototype.getLocalMatrix = function () {
  65033. return this._localMatrix;
  65034. };
  65035. Bone.prototype.getBaseMatrix = function () {
  65036. return this._baseMatrix;
  65037. };
  65038. Bone.prototype.getRestPose = function () {
  65039. return this._restPose;
  65040. };
  65041. Bone.prototype.returnToRest = function () {
  65042. this.updateMatrix(this._restPose.clone());
  65043. };
  65044. Bone.prototype.getWorldMatrix = function () {
  65045. return this._worldTransform;
  65046. };
  65047. Bone.prototype.getInvertedAbsoluteTransform = function () {
  65048. return this._invertedAbsoluteTransform;
  65049. };
  65050. Bone.prototype.getAbsoluteTransform = function () {
  65051. return this._absoluteTransform;
  65052. };
  65053. Object.defineProperty(Bone.prototype, "position", {
  65054. // Properties (matches AbstractMesh properties)
  65055. get: function () {
  65056. return this.getPosition();
  65057. },
  65058. set: function (newPosition) {
  65059. this.setPosition(newPosition);
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. Object.defineProperty(Bone.prototype, "rotation", {
  65065. get: function () {
  65066. return this.getRotation();
  65067. },
  65068. set: function (newRotation) {
  65069. this.setRotation(newRotation);
  65070. },
  65071. enumerable: true,
  65072. configurable: true
  65073. });
  65074. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  65075. get: function () {
  65076. return this.getRotationQuaternion();
  65077. },
  65078. set: function (newRotation) {
  65079. this.setRotationQuaternion(newRotation);
  65080. },
  65081. enumerable: true,
  65082. configurable: true
  65083. });
  65084. Object.defineProperty(Bone.prototype, "scaling", {
  65085. get: function () {
  65086. return this.getScale();
  65087. },
  65088. set: function (newScaling) {
  65089. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  65090. },
  65091. enumerable: true,
  65092. configurable: true
  65093. });
  65094. // Methods
  65095. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  65096. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65097. this._baseMatrix = matrix.clone();
  65098. this._localMatrix = matrix.clone();
  65099. this._skeleton._markAsDirty();
  65100. if (updateDifferenceMatrix) {
  65101. this._updateDifferenceMatrix();
  65102. }
  65103. };
  65104. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  65105. if (!rootMatrix) {
  65106. rootMatrix = this._baseMatrix;
  65107. }
  65108. if (this._parent) {
  65109. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65110. }
  65111. else {
  65112. this._absoluteTransform.copyFrom(rootMatrix);
  65113. }
  65114. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  65115. for (var index = 0; index < this.children.length; index++) {
  65116. this.children[index]._updateDifferenceMatrix();
  65117. }
  65118. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  65119. };
  65120. Bone.prototype.markAsDirty = function () {
  65121. this._currentRenderId++;
  65122. this._skeleton._markAsDirty();
  65123. };
  65124. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  65125. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  65126. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  65127. // all animation may be coming from a library skeleton, so may need to create animation
  65128. if (this.animations.length === 0) {
  65129. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  65130. this.animations[0].setKeys([]);
  65131. }
  65132. // get animation info / verify there is such a range from the source bone
  65133. var sourceRange = source.animations[0].getRange(rangeName);
  65134. if (!sourceRange) {
  65135. return false;
  65136. }
  65137. var from = sourceRange.from;
  65138. var to = sourceRange.to;
  65139. var sourceKeys = source.animations[0].getKeys();
  65140. // rescaling prep
  65141. var sourceBoneLength = source.length;
  65142. var sourceParent = source.getParent();
  65143. var parent = this.getParent();
  65144. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  65145. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  65146. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  65147. var destKeys = this.animations[0].getKeys();
  65148. // loop vars declaration
  65149. var orig;
  65150. var origTranslation;
  65151. var mat;
  65152. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  65153. orig = sourceKeys[key];
  65154. if (orig.frame >= from && orig.frame <= to) {
  65155. if (rescaleAsRequired) {
  65156. mat = orig.value.clone();
  65157. // scale based on parent ratio, when bone has parent
  65158. if (parentScalingReqd) {
  65159. origTranslation = mat.getTranslation();
  65160. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  65161. // scale based on skeleton dimension ratio when root bone, and value is passed
  65162. }
  65163. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  65164. origTranslation = mat.getTranslation();
  65165. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  65166. // use original when root bone, and no data for skelDimensionsRatio
  65167. }
  65168. else {
  65169. mat = orig.value;
  65170. }
  65171. }
  65172. else {
  65173. mat = orig.value;
  65174. }
  65175. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65176. }
  65177. }
  65178. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65179. return true;
  65180. };
  65181. /**
  65182. * Translate the bone in local or world space.
  65183. * @param vec The amount to translate the bone.
  65184. * @param space The space that the translation is in.
  65185. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65186. */
  65187. Bone.prototype.translate = function (vec, space, mesh) {
  65188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65189. var lm = this.getLocalMatrix();
  65190. if (space == BABYLON.Space.LOCAL) {
  65191. lm.m[12] += vec.x;
  65192. lm.m[13] += vec.y;
  65193. lm.m[14] += vec.z;
  65194. }
  65195. else {
  65196. var wm = null;
  65197. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65198. if (mesh) {
  65199. wm = mesh.getWorldMatrix();
  65200. }
  65201. this._skeleton.computeAbsoluteTransforms();
  65202. var tmat = Bone._tmpMats[0];
  65203. var tvec = Bone._tmpVecs[0];
  65204. if (this._parent) {
  65205. if (mesh && wm) {
  65206. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65207. tmat.multiplyToRef(wm, tmat);
  65208. }
  65209. else {
  65210. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65211. }
  65212. }
  65213. tmat.m[12] = 0;
  65214. tmat.m[13] = 0;
  65215. tmat.m[14] = 0;
  65216. tmat.invert();
  65217. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65218. lm.m[12] += tvec.x;
  65219. lm.m[13] += tvec.y;
  65220. lm.m[14] += tvec.z;
  65221. }
  65222. this.markAsDirty();
  65223. };
  65224. /**
  65225. * Set the postion of the bone in local or world space.
  65226. * @param position The position to set the bone.
  65227. * @param space The space that the position is in.
  65228. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65229. */
  65230. Bone.prototype.setPosition = function (position, space, mesh) {
  65231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65232. var lm = this.getLocalMatrix();
  65233. if (space == BABYLON.Space.LOCAL) {
  65234. lm.m[12] = position.x;
  65235. lm.m[13] = position.y;
  65236. lm.m[14] = position.z;
  65237. }
  65238. else {
  65239. var wm = null;
  65240. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65241. if (mesh) {
  65242. wm = mesh.getWorldMatrix();
  65243. }
  65244. this._skeleton.computeAbsoluteTransforms();
  65245. var tmat = Bone._tmpMats[0];
  65246. var vec = Bone._tmpVecs[0];
  65247. if (this._parent) {
  65248. if (mesh && wm) {
  65249. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65250. tmat.multiplyToRef(wm, tmat);
  65251. }
  65252. else {
  65253. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65254. }
  65255. }
  65256. tmat.invert();
  65257. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65258. lm.m[12] = vec.x;
  65259. lm.m[13] = vec.y;
  65260. lm.m[14] = vec.z;
  65261. }
  65262. this.markAsDirty();
  65263. };
  65264. /**
  65265. * Set the absolute postion of the bone (world space).
  65266. * @param position The position to set the bone.
  65267. * @param mesh The mesh that this bone is attached to.
  65268. */
  65269. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65270. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65271. };
  65272. /**
  65273. * Set the scale of the bone on the x, y and z axes.
  65274. * @param x The scale of the bone on the x axis.
  65275. * @param x The scale of the bone on the y axis.
  65276. * @param z The scale of the bone on the z axis.
  65277. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65278. */
  65279. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65280. if (scaleChildren === void 0) { scaleChildren = false; }
  65281. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65282. if (!scaleChildren) {
  65283. this._negateScaleChildren.x = 1 / x;
  65284. this._negateScaleChildren.y = 1 / y;
  65285. this._negateScaleChildren.z = 1 / z;
  65286. }
  65287. this._syncScaleVector();
  65288. }
  65289. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65290. };
  65291. /**
  65292. * Scale the bone on the x, y and z axes.
  65293. * @param x The amount to scale the bone on the x axis.
  65294. * @param x The amount to scale the bone on the y axis.
  65295. * @param z The amount to scale the bone on the z axis.
  65296. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65297. */
  65298. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65299. if (scaleChildren === void 0) { scaleChildren = false; }
  65300. var locMat = this.getLocalMatrix();
  65301. var origLocMat = Bone._tmpMats[0];
  65302. origLocMat.copyFrom(locMat);
  65303. var origLocMatInv = Bone._tmpMats[1];
  65304. origLocMatInv.copyFrom(origLocMat);
  65305. origLocMatInv.invert();
  65306. var scaleMat = Bone._tmpMats[2];
  65307. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65308. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65309. this._scaleVector.x *= x;
  65310. this._scaleVector.y *= y;
  65311. this._scaleVector.z *= z;
  65312. locMat.multiplyToRef(origLocMatInv, locMat);
  65313. locMat.multiplyToRef(scaleMat, locMat);
  65314. locMat.multiplyToRef(origLocMat, locMat);
  65315. var parent = this.getParent();
  65316. if (parent) {
  65317. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65318. }
  65319. else {
  65320. this.getAbsoluteTransform().copyFrom(locMat);
  65321. }
  65322. var len = this.children.length;
  65323. scaleMat.invert();
  65324. for (var i = 0; i < len; i++) {
  65325. var child = this.children[i];
  65326. var cm = child.getLocalMatrix();
  65327. cm.multiplyToRef(scaleMat, cm);
  65328. var lm = child.getLocalMatrix();
  65329. lm.m[12] *= x;
  65330. lm.m[13] *= y;
  65331. lm.m[14] *= z;
  65332. }
  65333. this.computeAbsoluteTransforms();
  65334. if (scaleChildren) {
  65335. for (var i = 0; i < len; i++) {
  65336. this.children[i].scale(x, y, z, scaleChildren);
  65337. }
  65338. }
  65339. this.markAsDirty();
  65340. };
  65341. /**
  65342. * Set the yaw, pitch, and roll of the bone in local or world space.
  65343. * @param yaw The rotation of the bone on the y axis.
  65344. * @param pitch The rotation of the bone on the x axis.
  65345. * @param roll The rotation of the bone on the z axis.
  65346. * @param space The space that the axes of rotation are in.
  65347. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65348. */
  65349. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65350. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65351. var rotMat = Bone._tmpMats[0];
  65352. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65353. var rotMatInv = Bone._tmpMats[1];
  65354. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65355. rotMatInv.multiplyToRef(rotMat, rotMat);
  65356. this._rotateWithMatrix(rotMat, space, mesh);
  65357. };
  65358. /**
  65359. * Rotate the bone on an axis in local or world space.
  65360. * @param axis The axis to rotate the bone on.
  65361. * @param amount The amount to rotate the bone.
  65362. * @param space The space that the axis is in.
  65363. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65364. */
  65365. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65366. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65367. var rmat = Bone._tmpMats[0];
  65368. rmat.m[12] = 0;
  65369. rmat.m[13] = 0;
  65370. rmat.m[14] = 0;
  65371. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65372. this._rotateWithMatrix(rmat, space, mesh);
  65373. };
  65374. /**
  65375. * Set the rotation of the bone to a particular axis angle in local or world space.
  65376. * @param axis The axis to rotate the bone on.
  65377. * @param angle The angle that the bone should be rotated to.
  65378. * @param space The space that the axis is in.
  65379. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65380. */
  65381. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65382. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65383. var rotMat = Bone._tmpMats[0];
  65384. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65385. var rotMatInv = Bone._tmpMats[1];
  65386. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65387. rotMatInv.multiplyToRef(rotMat, rotMat);
  65388. this._rotateWithMatrix(rotMat, space, mesh);
  65389. };
  65390. /**
  65391. * Set the euler rotation of the bone in local of world space.
  65392. * @param rotation The euler rotation that the bone should be set to.
  65393. * @param space The space that the rotation is in.
  65394. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65395. */
  65396. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65397. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65398. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65399. };
  65400. /**
  65401. * Set the quaternion rotation of the bone in local of world space.
  65402. * @param quat The quaternion rotation that the bone should be set to.
  65403. * @param space The space that the rotation is in.
  65404. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65405. */
  65406. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65407. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65408. var rotMatInv = Bone._tmpMats[0];
  65409. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65410. var rotMat = Bone._tmpMats[1];
  65411. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  65412. rotMatInv.multiplyToRef(rotMat, rotMat);
  65413. this._rotateWithMatrix(rotMat, space, mesh);
  65414. };
  65415. /**
  65416. * Set the rotation matrix of the bone in local of world space.
  65417. * @param rotMat The rotation matrix that the bone should be set to.
  65418. * @param space The space that the rotation is in.
  65419. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65420. */
  65421. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  65422. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65423. var rotMatInv = Bone._tmpMats[0];
  65424. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65425. var rotMat2 = Bone._tmpMats[1];
  65426. rotMat2.copyFrom(rotMat);
  65427. rotMatInv.multiplyToRef(rotMat, rotMat2);
  65428. this._rotateWithMatrix(rotMat2, space, mesh);
  65429. };
  65430. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  65431. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65432. var lmat = this.getLocalMatrix();
  65433. var lx = lmat.m[12];
  65434. var ly = lmat.m[13];
  65435. var lz = lmat.m[14];
  65436. var parent = this.getParent();
  65437. var parentScale = Bone._tmpMats[3];
  65438. var parentScaleInv = Bone._tmpMats[4];
  65439. if (parent) {
  65440. if (space == BABYLON.Space.WORLD) {
  65441. if (mesh) {
  65442. parentScale.copyFrom(mesh.getWorldMatrix());
  65443. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  65444. }
  65445. else {
  65446. parentScale.copyFrom(parent.getAbsoluteTransform());
  65447. }
  65448. }
  65449. else {
  65450. parentScale = parent._scaleMatrix;
  65451. }
  65452. parentScaleInv.copyFrom(parentScale);
  65453. parentScaleInv.invert();
  65454. lmat.multiplyToRef(parentScale, lmat);
  65455. lmat.multiplyToRef(rmat, lmat);
  65456. lmat.multiplyToRef(parentScaleInv, lmat);
  65457. }
  65458. else {
  65459. if (space == BABYLON.Space.WORLD && mesh) {
  65460. parentScale.copyFrom(mesh.getWorldMatrix());
  65461. parentScaleInv.copyFrom(parentScale);
  65462. parentScaleInv.invert();
  65463. lmat.multiplyToRef(parentScale, lmat);
  65464. lmat.multiplyToRef(rmat, lmat);
  65465. lmat.multiplyToRef(parentScaleInv, lmat);
  65466. }
  65467. else {
  65468. lmat.multiplyToRef(rmat, lmat);
  65469. }
  65470. }
  65471. lmat.m[12] = lx;
  65472. lmat.m[13] = ly;
  65473. lmat.m[14] = lz;
  65474. this.computeAbsoluteTransforms();
  65475. this.markAsDirty();
  65476. };
  65477. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  65478. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65479. if (space == BABYLON.Space.WORLD) {
  65480. var scaleMatrix = Bone._tmpMats[2];
  65481. scaleMatrix.copyFrom(this._scaleMatrix);
  65482. rotMatInv.copyFrom(this.getAbsoluteTransform());
  65483. if (mesh) {
  65484. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  65485. var meshScale = Bone._tmpMats[3];
  65486. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  65487. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  65488. }
  65489. rotMatInv.invert();
  65490. scaleMatrix.m[0] *= this._scalingDeterminant;
  65491. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65492. }
  65493. else {
  65494. rotMatInv.copyFrom(this.getLocalMatrix());
  65495. rotMatInv.invert();
  65496. var scaleMatrix = Bone._tmpMats[2];
  65497. scaleMatrix.copyFrom(this._scaleMatrix);
  65498. if (this._parent) {
  65499. var pscaleMatrix = Bone._tmpMats[3];
  65500. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  65501. pscaleMatrix.invert();
  65502. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  65503. }
  65504. else {
  65505. scaleMatrix.m[0] *= this._scalingDeterminant;
  65506. }
  65507. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65508. }
  65509. };
  65510. /**
  65511. * Get the scale of the bone
  65512. * @returns the scale of the bone
  65513. */
  65514. Bone.prototype.getScale = function () {
  65515. return this._scaleVector.clone();
  65516. };
  65517. /**
  65518. * Copy the scale of the bone to a vector3.
  65519. * @param result The vector3 to copy the scale to
  65520. */
  65521. Bone.prototype.getScaleToRef = function (result) {
  65522. result.copyFrom(this._scaleVector);
  65523. };
  65524. /**
  65525. * Get the position of the bone in local or world space.
  65526. * @param space The space that the returned position is in.
  65527. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65528. * @returns The position of the bone
  65529. */
  65530. Bone.prototype.getPosition = function (space, mesh) {
  65531. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65532. if (mesh === void 0) { mesh = null; }
  65533. var pos = BABYLON.Vector3.Zero();
  65534. this.getPositionToRef(space, mesh, pos);
  65535. return pos;
  65536. };
  65537. /**
  65538. * Copy the position of the bone to a vector3 in local or world space.
  65539. * @param space The space that the returned position is in.
  65540. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65541. * @param result The vector3 to copy the position to.
  65542. */
  65543. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  65544. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65545. if (space == BABYLON.Space.LOCAL) {
  65546. var lm = this.getLocalMatrix();
  65547. result.x = lm.m[12];
  65548. result.y = lm.m[13];
  65549. result.z = lm.m[14];
  65550. }
  65551. else {
  65552. var wm = null;
  65553. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65554. if (mesh) {
  65555. wm = mesh.getWorldMatrix();
  65556. }
  65557. this._skeleton.computeAbsoluteTransforms();
  65558. var tmat = Bone._tmpMats[0];
  65559. if (mesh && wm) {
  65560. tmat.copyFrom(this.getAbsoluteTransform());
  65561. tmat.multiplyToRef(wm, tmat);
  65562. }
  65563. else {
  65564. tmat = this.getAbsoluteTransform();
  65565. }
  65566. result.x = tmat.m[12];
  65567. result.y = tmat.m[13];
  65568. result.z = tmat.m[14];
  65569. }
  65570. };
  65571. /**
  65572. * Get the absolute position of the bone (world space).
  65573. * @param mesh The mesh that this bone is attached to.
  65574. * @returns The absolute position of the bone
  65575. */
  65576. Bone.prototype.getAbsolutePosition = function (mesh) {
  65577. if (mesh === void 0) { mesh = null; }
  65578. var pos = BABYLON.Vector3.Zero();
  65579. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  65580. return pos;
  65581. };
  65582. /**
  65583. * Copy the absolute position of the bone (world space) to the result param.
  65584. * @param mesh The mesh that this bone is attached to.
  65585. * @param result The vector3 to copy the absolute position to.
  65586. */
  65587. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  65588. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  65589. };
  65590. /**
  65591. * Compute the absolute transforms of this bone and its children.
  65592. */
  65593. Bone.prototype.computeAbsoluteTransforms = function () {
  65594. if (this._parent) {
  65595. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65596. }
  65597. else {
  65598. this._absoluteTransform.copyFrom(this._localMatrix);
  65599. var poseMatrix = this._skeleton.getPoseMatrix();
  65600. if (poseMatrix) {
  65601. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  65602. }
  65603. }
  65604. var children = this.children;
  65605. var len = children.length;
  65606. for (var i = 0; i < len; i++) {
  65607. children[i].computeAbsoluteTransforms();
  65608. }
  65609. };
  65610. Bone.prototype._syncScaleVector = function () {
  65611. var lm = this.getLocalMatrix();
  65612. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  65613. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  65614. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  65615. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  65616. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  65617. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  65618. this._scaleVector.x = xs * Math.sqrt(xsq);
  65619. this._scaleVector.y = ys * Math.sqrt(ysq);
  65620. this._scaleVector.z = zs * Math.sqrt(zsq);
  65621. if (this._parent) {
  65622. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  65623. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  65624. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  65625. }
  65626. 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);
  65627. };
  65628. /**
  65629. * Get the world direction from an axis that is in the local space of the bone.
  65630. * @param localAxis The local direction that is used to compute the world direction.
  65631. * @param mesh The mesh that this bone is attached to.
  65632. * @returns The world direction
  65633. */
  65634. Bone.prototype.getDirection = function (localAxis, mesh) {
  65635. if (mesh === void 0) { mesh = null; }
  65636. var result = BABYLON.Vector3.Zero();
  65637. this.getDirectionToRef(localAxis, mesh, result);
  65638. return result;
  65639. };
  65640. /**
  65641. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  65642. * @param localAxis The local direction that is used to compute the world direction.
  65643. * @param mesh The mesh that this bone is attached to.
  65644. * @param result The vector3 that the world direction will be copied to.
  65645. */
  65646. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  65647. if (mesh === void 0) { mesh = null; }
  65648. var wm = null;
  65649. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65650. if (mesh) {
  65651. wm = mesh.getWorldMatrix();
  65652. }
  65653. this._skeleton.computeAbsoluteTransforms();
  65654. var mat = Bone._tmpMats[0];
  65655. mat.copyFrom(this.getAbsoluteTransform());
  65656. if (mesh && wm) {
  65657. mat.multiplyToRef(wm, mat);
  65658. }
  65659. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  65660. result.normalize();
  65661. };
  65662. /**
  65663. * Get the euler rotation of the bone in local or world space.
  65664. * @param space The space that the rotation should be in.
  65665. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65666. * @returns The euler rotation
  65667. */
  65668. Bone.prototype.getRotation = function (space, mesh) {
  65669. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65670. if (mesh === void 0) { mesh = null; }
  65671. var result = BABYLON.Vector3.Zero();
  65672. this.getRotationToRef(space, mesh, result);
  65673. return result;
  65674. };
  65675. /**
  65676. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  65677. * @param space The space that the rotation should be in.
  65678. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65679. * @param result The vector3 that the rotation should be copied to.
  65680. */
  65681. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  65682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65683. if (mesh === void 0) { mesh = null; }
  65684. var quat = Bone._tmpQuat;
  65685. this.getRotationQuaternionToRef(space, mesh, quat);
  65686. quat.toEulerAnglesToRef(result);
  65687. };
  65688. /**
  65689. * Get the quaternion rotation of the bone in either local or world space.
  65690. * @param space The space that the rotation should be in.
  65691. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65692. * @returns The quaternion rotation
  65693. */
  65694. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  65695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65696. if (mesh === void 0) { mesh = null; }
  65697. var result = BABYLON.Quaternion.Identity();
  65698. this.getRotationQuaternionToRef(space, mesh, result);
  65699. return result;
  65700. };
  65701. /**
  65702. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  65703. * @param space The space that the rotation should be in.
  65704. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65705. * @param result The quaternion that the rotation should be copied to.
  65706. */
  65707. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  65708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65709. if (mesh === void 0) { mesh = null; }
  65710. if (space == BABYLON.Space.LOCAL) {
  65711. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65712. }
  65713. else {
  65714. var mat = Bone._tmpMats[0];
  65715. var amat = this.getAbsoluteTransform();
  65716. if (mesh) {
  65717. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65718. }
  65719. else {
  65720. mat.copyFrom(amat);
  65721. }
  65722. mat.m[0] *= this._scalingDeterminant;
  65723. mat.m[1] *= this._scalingDeterminant;
  65724. mat.m[2] *= this._scalingDeterminant;
  65725. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65726. }
  65727. };
  65728. /**
  65729. * Get the rotation matrix of the bone in local or world space.
  65730. * @param space The space that the rotation should be in.
  65731. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65732. * @returns The rotation matrix
  65733. */
  65734. Bone.prototype.getRotationMatrix = function (space, mesh) {
  65735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65736. var result = BABYLON.Matrix.Identity();
  65737. this.getRotationMatrixToRef(space, mesh, result);
  65738. return result;
  65739. };
  65740. /**
  65741. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  65742. * @param space The space that the rotation should be in.
  65743. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65744. * @param result The quaternion that the rotation should be copied to.
  65745. */
  65746. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  65747. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65748. if (space == BABYLON.Space.LOCAL) {
  65749. this.getLocalMatrix().getRotationMatrixToRef(result);
  65750. }
  65751. else {
  65752. var mat = Bone._tmpMats[0];
  65753. var amat = this.getAbsoluteTransform();
  65754. if (mesh) {
  65755. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65756. }
  65757. else {
  65758. mat.copyFrom(amat);
  65759. }
  65760. mat.m[0] *= this._scalingDeterminant;
  65761. mat.m[1] *= this._scalingDeterminant;
  65762. mat.m[2] *= this._scalingDeterminant;
  65763. mat.getRotationMatrixToRef(result);
  65764. }
  65765. };
  65766. /**
  65767. * Get the world position of a point that is in the local space of the bone.
  65768. * @param position The local position
  65769. * @param mesh The mesh that this bone is attached to.
  65770. * @returns The world position
  65771. */
  65772. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  65773. if (mesh === void 0) { mesh = null; }
  65774. var result = BABYLON.Vector3.Zero();
  65775. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  65776. return result;
  65777. };
  65778. /**
  65779. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  65780. * @param position The local position
  65781. * @param mesh The mesh that this bone is attached to.
  65782. * @param result The vector3 that the world position should be copied to.
  65783. */
  65784. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  65785. if (mesh === void 0) { mesh = null; }
  65786. var wm = null;
  65787. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65788. if (mesh) {
  65789. wm = mesh.getWorldMatrix();
  65790. }
  65791. this._skeleton.computeAbsoluteTransforms();
  65792. var tmat = Bone._tmpMats[0];
  65793. if (mesh && wm) {
  65794. tmat.copyFrom(this.getAbsoluteTransform());
  65795. tmat.multiplyToRef(wm, tmat);
  65796. }
  65797. else {
  65798. tmat = this.getAbsoluteTransform();
  65799. }
  65800. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65801. };
  65802. /**
  65803. * Get the local position of a point that is in world space.
  65804. * @param position The world position
  65805. * @param mesh The mesh that this bone is attached to.
  65806. * @returns The local position
  65807. */
  65808. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  65809. if (mesh === void 0) { mesh = null; }
  65810. var result = BABYLON.Vector3.Zero();
  65811. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  65812. return result;
  65813. };
  65814. /**
  65815. * Get the local position of a point that is in world space and copy it to the result param.
  65816. * @param position The world position
  65817. * @param mesh The mesh that this bone is attached to.
  65818. * @param result The vector3 that the local position should be copied to.
  65819. */
  65820. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  65821. if (mesh === void 0) { mesh = null; }
  65822. var wm = null;
  65823. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65824. if (mesh) {
  65825. wm = mesh.getWorldMatrix();
  65826. }
  65827. this._skeleton.computeAbsoluteTransforms();
  65828. var tmat = Bone._tmpMats[0];
  65829. tmat.copyFrom(this.getAbsoluteTransform());
  65830. if (mesh && wm) {
  65831. tmat.multiplyToRef(wm, tmat);
  65832. }
  65833. tmat.invert();
  65834. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65835. };
  65836. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65837. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  65838. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  65839. return Bone;
  65840. }(BABYLON.Node));
  65841. BABYLON.Bone = Bone;
  65842. })(BABYLON || (BABYLON = {}));
  65843. //# sourceMappingURL=babylon.bone.js.map
  65844. var BABYLON;
  65845. (function (BABYLON) {
  65846. var BoneIKController = /** @class */ (function () {
  65847. function BoneIKController(mesh, bone, options) {
  65848. this.targetPosition = BABYLON.Vector3.Zero();
  65849. this.poleTargetPosition = BABYLON.Vector3.Zero();
  65850. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  65851. this.poleAngle = 0;
  65852. this.slerpAmount = 1;
  65853. this._bone1Quat = BABYLON.Quaternion.Identity();
  65854. this._bone1Mat = BABYLON.Matrix.Identity();
  65855. this._bone2Ang = Math.PI;
  65856. this._maxAngle = Math.PI;
  65857. this._rightHandedSystem = false;
  65858. this._bendAxis = BABYLON.Vector3.Right();
  65859. this._slerping = false;
  65860. this._adjustRoll = 0;
  65861. this._bone2 = bone;
  65862. this._bone1 = bone.getParent();
  65863. if (!this._bone1) {
  65864. return;
  65865. }
  65866. this.mesh = mesh;
  65867. var bonePos = bone.getPosition();
  65868. if (bone.getAbsoluteTransform().determinant() > 0) {
  65869. this._rightHandedSystem = true;
  65870. this._bendAxis.x = 0;
  65871. this._bendAxis.y = 0;
  65872. this._bendAxis.z = -1;
  65873. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  65874. this._adjustRoll = Math.PI * .5;
  65875. this._bendAxis.z = 1;
  65876. }
  65877. }
  65878. if (this._bone1.length) {
  65879. var boneScale1 = this._bone1.getScale();
  65880. var boneScale2 = this._bone2.getScale();
  65881. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  65882. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  65883. }
  65884. else if (this._bone1.children[0]) {
  65885. mesh.computeWorldMatrix(true);
  65886. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  65887. var pos2 = this._bone2.getAbsolutePosition(mesh);
  65888. var pos3 = this._bone1.getAbsolutePosition(mesh);
  65889. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  65890. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  65891. }
  65892. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  65893. this.maxAngle = Math.PI;
  65894. if (options) {
  65895. if (options.targetMesh) {
  65896. this.targetMesh = options.targetMesh;
  65897. this.targetMesh.computeWorldMatrix(true);
  65898. }
  65899. if (options.poleTargetMesh) {
  65900. this.poleTargetMesh = options.poleTargetMesh;
  65901. this.poleTargetMesh.computeWorldMatrix(true);
  65902. }
  65903. else if (options.poleTargetBone) {
  65904. this.poleTargetBone = options.poleTargetBone;
  65905. }
  65906. else if (this._bone1.getParent()) {
  65907. this.poleTargetBone = this._bone1.getParent();
  65908. }
  65909. if (options.poleTargetLocalOffset) {
  65910. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  65911. }
  65912. if (options.poleAngle) {
  65913. this.poleAngle = options.poleAngle;
  65914. }
  65915. if (options.bendAxis) {
  65916. this._bendAxis.copyFrom(options.bendAxis);
  65917. }
  65918. if (options.maxAngle) {
  65919. this.maxAngle = options.maxAngle;
  65920. }
  65921. if (options.slerpAmount) {
  65922. this.slerpAmount = options.slerpAmount;
  65923. }
  65924. }
  65925. }
  65926. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  65927. get: function () {
  65928. return this._maxAngle;
  65929. },
  65930. set: function (value) {
  65931. this._setMaxAngle(value);
  65932. },
  65933. enumerable: true,
  65934. configurable: true
  65935. });
  65936. BoneIKController.prototype._setMaxAngle = function (ang) {
  65937. if (ang < 0) {
  65938. ang = 0;
  65939. }
  65940. if (ang > Math.PI || ang == undefined) {
  65941. ang = Math.PI;
  65942. }
  65943. this._maxAngle = ang;
  65944. var a = this._bone1Length;
  65945. var b = this._bone2Length;
  65946. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  65947. };
  65948. BoneIKController.prototype.update = function () {
  65949. var bone1 = this._bone1;
  65950. if (!bone1) {
  65951. return;
  65952. }
  65953. var target = this.targetPosition;
  65954. var poleTarget = this.poleTargetPosition;
  65955. var mat1 = BoneIKController._tmpMats[0];
  65956. var mat2 = BoneIKController._tmpMats[1];
  65957. if (this.targetMesh) {
  65958. target.copyFrom(this.targetMesh.getAbsolutePosition());
  65959. }
  65960. if (this.poleTargetBone) {
  65961. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  65962. }
  65963. else if (this.poleTargetMesh) {
  65964. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  65965. }
  65966. var bonePos = BoneIKController._tmpVecs[0];
  65967. var zaxis = BoneIKController._tmpVecs[1];
  65968. var xaxis = BoneIKController._tmpVecs[2];
  65969. var yaxis = BoneIKController._tmpVecs[3];
  65970. var upAxis = BoneIKController._tmpVecs[4];
  65971. var _tmpQuat = BoneIKController._tmpQuat;
  65972. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  65973. poleTarget.subtractToRef(bonePos, upAxis);
  65974. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  65975. upAxis.y = 1;
  65976. }
  65977. else {
  65978. upAxis.normalize();
  65979. }
  65980. target.subtractToRef(bonePos, yaxis);
  65981. yaxis.normalize();
  65982. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  65983. zaxis.normalize();
  65984. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  65985. xaxis.normalize();
  65986. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  65987. var a = this._bone1Length;
  65988. var b = this._bone2Length;
  65989. var c = BABYLON.Vector3.Distance(bonePos, target);
  65990. if (this._maxReach > 0) {
  65991. c = Math.min(this._maxReach, c);
  65992. }
  65993. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  65994. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  65995. if (acosa > 1) {
  65996. acosa = 1;
  65997. }
  65998. if (acosb > 1) {
  65999. acosb = 1;
  66000. }
  66001. if (acosa < -1) {
  66002. acosa = -1;
  66003. }
  66004. if (acosb < -1) {
  66005. acosb = -1;
  66006. }
  66007. var angA = Math.acos(acosa);
  66008. var angB = Math.acos(acosb);
  66009. var angC = -angA - angB;
  66010. if (this._rightHandedSystem) {
  66011. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  66012. mat2.multiplyToRef(mat1, mat1);
  66013. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  66014. mat2.multiplyToRef(mat1, mat1);
  66015. }
  66016. else {
  66017. var _tmpVec = BoneIKController._tmpVecs[5];
  66018. _tmpVec.copyFrom(this._bendAxis);
  66019. _tmpVec.x *= -1;
  66020. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  66021. mat2.multiplyToRef(mat1, mat1);
  66022. }
  66023. if (this.poleAngle) {
  66024. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  66025. mat1.multiplyToRef(mat2, mat1);
  66026. }
  66027. if (this._bone1) {
  66028. if (this.slerpAmount < 1) {
  66029. if (!this._slerping) {
  66030. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  66031. }
  66032. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  66033. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  66034. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  66035. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  66036. this._slerping = true;
  66037. }
  66038. else {
  66039. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  66040. this._bone1Mat.copyFrom(mat1);
  66041. this._slerping = false;
  66042. }
  66043. }
  66044. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  66045. this._bone2Ang = angC;
  66046. };
  66047. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66048. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  66049. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66050. return BoneIKController;
  66051. }());
  66052. BABYLON.BoneIKController = BoneIKController;
  66053. })(BABYLON || (BABYLON = {}));
  66054. //# sourceMappingURL=babylon.boneIKController.js.map
  66055. var BABYLON;
  66056. (function (BABYLON) {
  66057. var BoneLookController = /** @class */ (function () {
  66058. /**
  66059. * Create a BoneLookController
  66060. * @param mesh the mesh that the bone belongs to
  66061. * @param bone the bone that will be looking to the target
  66062. * @param target the target Vector3 to look at
  66063. * @param settings optional settings:
  66064. * - maxYaw: the maximum angle the bone will yaw to
  66065. * - minYaw: the minimum angle the bone will yaw to
  66066. * - maxPitch: the maximum angle the bone will pitch to
  66067. * - minPitch: the minimum angle the bone will yaw to
  66068. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  66069. * - upAxis: the up axis of the coordinate system
  66070. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66071. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  66072. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  66073. * - adjustYaw: used to make an adjustment to the yaw of the bone
  66074. * - adjustPitch: used to make an adjustment to the pitch of the bone
  66075. * - adjustRoll: used to make an adjustment to the roll of the bone
  66076. **/
  66077. function BoneLookController(mesh, bone, target, options) {
  66078. /**
  66079. * The up axis of the coordinate system that is used when the bone is rotated.
  66080. */
  66081. this.upAxis = BABYLON.Vector3.Up();
  66082. /**
  66083. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66084. */
  66085. this.upAxisSpace = BABYLON.Space.LOCAL;
  66086. /**
  66087. * Used to make an adjustment to the yaw of the bone.
  66088. */
  66089. this.adjustYaw = 0;
  66090. /**
  66091. * Used to make an adjustment to the pitch of the bone.
  66092. */
  66093. this.adjustPitch = 0;
  66094. /**
  66095. * Used to make an adjustment to the roll of the bone.
  66096. */
  66097. this.adjustRoll = 0;
  66098. /**
  66099. * 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).
  66100. */
  66101. this.slerpAmount = 1;
  66102. this._boneQuat = BABYLON.Quaternion.Identity();
  66103. this._slerping = false;
  66104. this._firstFrameSkipped = false;
  66105. this._fowardAxis = BABYLON.Vector3.Forward();
  66106. this.mesh = mesh;
  66107. this.bone = bone;
  66108. this.target = target;
  66109. if (options) {
  66110. if (options.adjustYaw) {
  66111. this.adjustYaw = options.adjustYaw;
  66112. }
  66113. if (options.adjustPitch) {
  66114. this.adjustPitch = options.adjustPitch;
  66115. }
  66116. if (options.adjustRoll) {
  66117. this.adjustRoll = options.adjustRoll;
  66118. }
  66119. if (options.maxYaw != null) {
  66120. this.maxYaw = options.maxYaw;
  66121. }
  66122. else {
  66123. this.maxYaw = Math.PI;
  66124. }
  66125. if (options.minYaw != null) {
  66126. this.minYaw = options.minYaw;
  66127. }
  66128. else {
  66129. this.minYaw = -Math.PI;
  66130. }
  66131. if (options.maxPitch != null) {
  66132. this.maxPitch = options.maxPitch;
  66133. }
  66134. else {
  66135. this.maxPitch = Math.PI;
  66136. }
  66137. if (options.minPitch != null) {
  66138. this.minPitch = options.minPitch;
  66139. }
  66140. else {
  66141. this.minPitch = -Math.PI;
  66142. }
  66143. if (options.slerpAmount != null) {
  66144. this.slerpAmount = options.slerpAmount;
  66145. }
  66146. if (options.upAxis != null) {
  66147. this.upAxis = options.upAxis;
  66148. }
  66149. if (options.upAxisSpace != null) {
  66150. this.upAxisSpace = options.upAxisSpace;
  66151. }
  66152. if (options.yawAxis != null || options.pitchAxis != null) {
  66153. var newYawAxis = BABYLON.Axis.Y;
  66154. var newPitchAxis = BABYLON.Axis.X;
  66155. if (options.yawAxis != null) {
  66156. newYawAxis = options.yawAxis.clone();
  66157. newYawAxis.normalize();
  66158. }
  66159. if (options.pitchAxis != null) {
  66160. newPitchAxis = options.pitchAxis.clone();
  66161. newPitchAxis.normalize();
  66162. }
  66163. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  66164. this._transformYawPitch = BABYLON.Matrix.Identity();
  66165. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  66166. this._transformYawPitchInv = this._transformYawPitch.clone();
  66167. this._transformYawPitch.invert();
  66168. }
  66169. }
  66170. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  66171. this.upAxisSpace = BABYLON.Space.LOCAL;
  66172. }
  66173. }
  66174. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  66175. /**
  66176. * Get/set the minimum yaw angle that the bone can look to.
  66177. */
  66178. get: function () {
  66179. return this._minYaw;
  66180. },
  66181. set: function (value) {
  66182. this._minYaw = value;
  66183. this._minYawSin = Math.sin(value);
  66184. this._minYawCos = Math.cos(value);
  66185. if (this._maxYaw != null) {
  66186. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66187. this._yawRange = this._maxYaw - this._minYaw;
  66188. }
  66189. },
  66190. enumerable: true,
  66191. configurable: true
  66192. });
  66193. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66194. /**
  66195. * Get/set the maximum yaw angle that the bone can look to.
  66196. */
  66197. get: function () {
  66198. return this._maxYaw;
  66199. },
  66200. set: function (value) {
  66201. this._maxYaw = value;
  66202. this._maxYawSin = Math.sin(value);
  66203. this._maxYawCos = Math.cos(value);
  66204. if (this._minYaw != null) {
  66205. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66206. this._yawRange = this._maxYaw - this._minYaw;
  66207. }
  66208. },
  66209. enumerable: true,
  66210. configurable: true
  66211. });
  66212. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66213. /**
  66214. * Get/set the minimum pitch angle that the bone can look to.
  66215. */
  66216. get: function () {
  66217. return this._minPitch;
  66218. },
  66219. set: function (value) {
  66220. this._minPitch = value;
  66221. this._minPitchTan = Math.tan(value);
  66222. },
  66223. enumerable: true,
  66224. configurable: true
  66225. });
  66226. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66227. /**
  66228. * Get/set the maximum pitch angle that the bone can look to.
  66229. */
  66230. get: function () {
  66231. return this._maxPitch;
  66232. },
  66233. set: function (value) {
  66234. this._maxPitch = value;
  66235. this._maxPitchTan = Math.tan(value);
  66236. },
  66237. enumerable: true,
  66238. configurable: true
  66239. });
  66240. /**
  66241. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66242. */
  66243. BoneLookController.prototype.update = function () {
  66244. //skip the first frame when slerping so that the mesh rotation is correct
  66245. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66246. this._firstFrameSkipped = true;
  66247. return;
  66248. }
  66249. var bone = this.bone;
  66250. var bonePos = BoneLookController._tmpVecs[0];
  66251. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66252. var target = this.target;
  66253. var _tmpMat1 = BoneLookController._tmpMats[0];
  66254. var _tmpMat2 = BoneLookController._tmpMats[1];
  66255. var mesh = this.mesh;
  66256. var parentBone = bone.getParent();
  66257. var upAxis = BoneLookController._tmpVecs[1];
  66258. upAxis.copyFrom(this.upAxis);
  66259. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66260. if (this._transformYawPitch) {
  66261. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66262. }
  66263. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66264. }
  66265. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66266. mesh.getDirectionToRef(upAxis, upAxis);
  66267. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66268. upAxis.normalize();
  66269. }
  66270. }
  66271. var checkYaw = false;
  66272. var checkPitch = false;
  66273. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66274. checkYaw = true;
  66275. }
  66276. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66277. checkPitch = true;
  66278. }
  66279. if (checkYaw || checkPitch) {
  66280. var spaceMat = BoneLookController._tmpMats[2];
  66281. var spaceMatInv = BoneLookController._tmpMats[3];
  66282. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66283. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66284. }
  66285. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66286. spaceMat.copyFrom(mesh.getWorldMatrix());
  66287. }
  66288. else {
  66289. var forwardAxis = BoneLookController._tmpVecs[2];
  66290. forwardAxis.copyFrom(this._fowardAxis);
  66291. if (this._transformYawPitch) {
  66292. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66293. }
  66294. if (parentBone) {
  66295. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66296. }
  66297. else {
  66298. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66299. }
  66300. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66301. rightAxis.normalize();
  66302. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66303. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66304. }
  66305. spaceMat.invertToRef(spaceMatInv);
  66306. var xzlen = null;
  66307. if (checkPitch) {
  66308. var localTarget = BoneLookController._tmpVecs[3];
  66309. target.subtractToRef(bonePos, localTarget);
  66310. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66311. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66312. var pitch = Math.atan2(localTarget.y, xzlen);
  66313. var newPitch = pitch;
  66314. if (pitch > this._maxPitch) {
  66315. localTarget.y = this._maxPitchTan * xzlen;
  66316. newPitch = this._maxPitch;
  66317. }
  66318. else if (pitch < this._minPitch) {
  66319. localTarget.y = this._minPitchTan * xzlen;
  66320. newPitch = this._minPitch;
  66321. }
  66322. if (pitch != newPitch) {
  66323. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66324. localTarget.addInPlace(bonePos);
  66325. target = localTarget;
  66326. }
  66327. }
  66328. if (checkYaw) {
  66329. var localTarget = BoneLookController._tmpVecs[4];
  66330. target.subtractToRef(bonePos, localTarget);
  66331. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66332. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66333. var newYaw = yaw;
  66334. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66335. if (xzlen == null) {
  66336. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66337. }
  66338. if (this._yawRange > Math.PI) {
  66339. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66340. localTarget.z = this._maxYawCos * xzlen;
  66341. localTarget.x = this._maxYawSin * xzlen;
  66342. newYaw = this._maxYaw;
  66343. }
  66344. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66345. localTarget.z = this._minYawCos * xzlen;
  66346. localTarget.x = this._minYawSin * xzlen;
  66347. newYaw = this._minYaw;
  66348. }
  66349. }
  66350. else {
  66351. if (yaw > this._maxYaw) {
  66352. localTarget.z = this._maxYawCos * xzlen;
  66353. localTarget.x = this._maxYawSin * xzlen;
  66354. newYaw = this._maxYaw;
  66355. }
  66356. else if (yaw < this._minYaw) {
  66357. localTarget.z = this._minYawCos * xzlen;
  66358. localTarget.x = this._minYawSin * xzlen;
  66359. newYaw = this._minYaw;
  66360. }
  66361. }
  66362. }
  66363. if (this._slerping && this._yawRange > Math.PI) {
  66364. //are we going to be crossing into the min/max region?
  66365. var boneFwd = BoneLookController._tmpVecs[8];
  66366. boneFwd.copyFrom(BABYLON.Axis.Z);
  66367. if (this._transformYawPitch) {
  66368. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66369. }
  66370. var boneRotMat = BoneLookController._tmpMats[4];
  66371. this._boneQuat.toRotationMatrix(boneRotMat);
  66372. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66373. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66374. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66375. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66376. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66377. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66378. if (angBtwTar > angBtwMidYaw) {
  66379. if (xzlen == null) {
  66380. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66381. }
  66382. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66383. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66384. if (angBtwMin < angBtwMax) {
  66385. newYaw = boneYaw + Math.PI * .75;
  66386. localTarget.z = Math.cos(newYaw) * xzlen;
  66387. localTarget.x = Math.sin(newYaw) * xzlen;
  66388. }
  66389. else {
  66390. newYaw = boneYaw - Math.PI * .75;
  66391. localTarget.z = Math.cos(newYaw) * xzlen;
  66392. localTarget.x = Math.sin(newYaw) * xzlen;
  66393. }
  66394. }
  66395. }
  66396. if (yaw != newYaw) {
  66397. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66398. localTarget.addInPlace(bonePos);
  66399. target = localTarget;
  66400. }
  66401. }
  66402. }
  66403. var zaxis = BoneLookController._tmpVecs[5];
  66404. var xaxis = BoneLookController._tmpVecs[6];
  66405. var yaxis = BoneLookController._tmpVecs[7];
  66406. var _tmpQuat = BoneLookController._tmpQuat;
  66407. target.subtractToRef(bonePos, zaxis);
  66408. zaxis.normalize();
  66409. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  66410. xaxis.normalize();
  66411. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  66412. yaxis.normalize();
  66413. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  66414. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  66415. return;
  66416. }
  66417. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  66418. return;
  66419. }
  66420. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  66421. return;
  66422. }
  66423. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  66424. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  66425. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  66426. }
  66427. if (this.slerpAmount < 1) {
  66428. if (!this._slerping) {
  66429. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  66430. }
  66431. if (this._transformYawPitch) {
  66432. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66433. }
  66434. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  66435. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  66436. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  66437. this._slerping = true;
  66438. }
  66439. else {
  66440. if (this._transformYawPitch) {
  66441. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66442. }
  66443. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  66444. this._slerping = false;
  66445. }
  66446. };
  66447. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  66448. var angDiff = ang2 - ang1;
  66449. angDiff %= Math.PI * 2;
  66450. if (angDiff > Math.PI) {
  66451. angDiff -= Math.PI * 2;
  66452. }
  66453. else if (angDiff < -Math.PI) {
  66454. angDiff += Math.PI * 2;
  66455. }
  66456. return angDiff;
  66457. };
  66458. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  66459. ang1 %= (2 * Math.PI);
  66460. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66461. ang2 %= (2 * Math.PI);
  66462. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66463. var ab = 0;
  66464. if (ang1 < ang2) {
  66465. ab = ang2 - ang1;
  66466. }
  66467. else {
  66468. ab = ang1 - ang2;
  66469. }
  66470. if (ab > Math.PI) {
  66471. ab = Math.PI * 2 - ab;
  66472. }
  66473. return ab;
  66474. };
  66475. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  66476. ang %= (2 * Math.PI);
  66477. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  66478. ang1 %= (2 * Math.PI);
  66479. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66480. ang2 %= (2 * Math.PI);
  66481. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66482. if (ang1 < ang2) {
  66483. if (ang > ang1 && ang < ang2) {
  66484. return true;
  66485. }
  66486. }
  66487. else {
  66488. if (ang > ang2 && ang < ang1) {
  66489. return true;
  66490. }
  66491. }
  66492. return false;
  66493. };
  66494. 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()];
  66495. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  66496. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66497. return BoneLookController;
  66498. }());
  66499. BABYLON.BoneLookController = BoneLookController;
  66500. })(BABYLON || (BABYLON = {}));
  66501. //# sourceMappingURL=babylon.boneLookController.js.map
  66502. var BABYLON;
  66503. (function (BABYLON) {
  66504. var Skeleton = /** @class */ (function () {
  66505. function Skeleton(name, id, scene) {
  66506. this.name = name;
  66507. this.id = id;
  66508. this.bones = new Array();
  66509. this.needInitialSkinMatrix = false;
  66510. this._isDirty = true;
  66511. this._meshesWithPoseMatrix = new Array();
  66512. this._identity = BABYLON.Matrix.Identity();
  66513. this._ranges = {};
  66514. this._lastAbsoluteTransformsUpdateId = -1;
  66515. // Events
  66516. /**
  66517. * An event triggered before computing the skeleton's matrices
  66518. * @type {BABYLON.Observable}
  66519. */
  66520. this.onBeforeComputeObservable = new BABYLON.Observable();
  66521. this.bones = [];
  66522. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66523. scene.skeletons.push(this);
  66524. //make sure it will recalculate the matrix next time prepare is called.
  66525. this._isDirty = true;
  66526. }
  66527. // Members
  66528. Skeleton.prototype.getTransformMatrices = function (mesh) {
  66529. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  66530. return mesh._bonesTransformMatrices;
  66531. }
  66532. if (!this._transformMatrices) {
  66533. this.prepare();
  66534. }
  66535. return this._transformMatrices;
  66536. };
  66537. Skeleton.prototype.getScene = function () {
  66538. return this._scene;
  66539. };
  66540. // Methods
  66541. /**
  66542. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  66543. */
  66544. Skeleton.prototype.toString = function (fullDetails) {
  66545. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  66546. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  66547. if (fullDetails) {
  66548. ret += ", Ranges: {";
  66549. var first = true;
  66550. for (var name_1 in this._ranges) {
  66551. if (first) {
  66552. ret += ", ";
  66553. first = false;
  66554. }
  66555. ret += name_1;
  66556. }
  66557. ret += "}";
  66558. }
  66559. return ret;
  66560. };
  66561. /**
  66562. * Get bone's index searching by name
  66563. * @param {string} name is bone's name to search for
  66564. * @return {number} Indice of the bone. Returns -1 if not found
  66565. */
  66566. Skeleton.prototype.getBoneIndexByName = function (name) {
  66567. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  66568. if (this.bones[boneIndex].name === name) {
  66569. return boneIndex;
  66570. }
  66571. }
  66572. return -1;
  66573. };
  66574. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  66575. // check name not already in use
  66576. if (!this._ranges[name]) {
  66577. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  66578. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66579. if (this.bones[i].animations[0]) {
  66580. this.bones[i].animations[0].createRange(name, from, to);
  66581. }
  66582. }
  66583. }
  66584. };
  66585. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  66586. if (deleteFrames === void 0) { deleteFrames = true; }
  66587. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66588. if (this.bones[i].animations[0]) {
  66589. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  66590. }
  66591. }
  66592. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  66593. };
  66594. Skeleton.prototype.getAnimationRange = function (name) {
  66595. return this._ranges[name];
  66596. };
  66597. /**
  66598. * Returns as an Array, all AnimationRanges defined on this skeleton
  66599. */
  66600. Skeleton.prototype.getAnimationRanges = function () {
  66601. var animationRanges = [];
  66602. var name;
  66603. var i = 0;
  66604. for (name in this._ranges) {
  66605. animationRanges[i] = this._ranges[name];
  66606. i++;
  66607. }
  66608. return animationRanges;
  66609. };
  66610. /**
  66611. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  66612. */
  66613. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  66614. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66615. if (this._ranges[name] || !source.getAnimationRange(name)) {
  66616. return false;
  66617. }
  66618. var ret = true;
  66619. var frameOffset = this._getHighestAnimationFrame() + 1;
  66620. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  66621. var boneDict = {};
  66622. var sourceBones = source.bones;
  66623. var nBones;
  66624. var i;
  66625. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  66626. boneDict[sourceBones[i].name] = sourceBones[i];
  66627. }
  66628. if (this.bones.length !== sourceBones.length) {
  66629. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  66630. ret = false;
  66631. }
  66632. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  66633. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  66634. var boneName = this.bones[i].name;
  66635. var sourceBone = boneDict[boneName];
  66636. if (sourceBone) {
  66637. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  66638. }
  66639. else {
  66640. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  66641. ret = false;
  66642. }
  66643. }
  66644. // do not call createAnimationRange(), since it also is done to bones, which was already done
  66645. var range = source.getAnimationRange(name);
  66646. if (range) {
  66647. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  66648. }
  66649. return ret;
  66650. };
  66651. Skeleton.prototype.returnToRest = function () {
  66652. for (var index = 0; index < this.bones.length; index++) {
  66653. this.bones[index].returnToRest();
  66654. }
  66655. };
  66656. Skeleton.prototype._getHighestAnimationFrame = function () {
  66657. var ret = 0;
  66658. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66659. if (this.bones[i].animations[0]) {
  66660. var highest = this.bones[i].animations[0].getHighestFrame();
  66661. if (ret < highest) {
  66662. ret = highest;
  66663. }
  66664. }
  66665. }
  66666. return ret;
  66667. };
  66668. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  66669. var range = this.getAnimationRange(name);
  66670. if (!range) {
  66671. return null;
  66672. }
  66673. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  66674. };
  66675. Skeleton.prototype._markAsDirty = function () {
  66676. this._isDirty = true;
  66677. };
  66678. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  66679. this._meshesWithPoseMatrix.push(mesh);
  66680. };
  66681. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  66682. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  66683. if (index > -1) {
  66684. this._meshesWithPoseMatrix.splice(index, 1);
  66685. }
  66686. };
  66687. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  66688. this.onBeforeComputeObservable.notifyObservers(this);
  66689. for (var index = 0; index < this.bones.length; index++) {
  66690. var bone = this.bones[index];
  66691. var parentBone = bone.getParent();
  66692. if (parentBone) {
  66693. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  66694. }
  66695. else {
  66696. if (initialSkinMatrix) {
  66697. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  66698. }
  66699. else {
  66700. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  66701. }
  66702. }
  66703. if (bone._index !== -1) {
  66704. var mappedIndex = bone._index === null ? index : bone._index;
  66705. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  66706. }
  66707. }
  66708. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  66709. };
  66710. Skeleton.prototype.prepare = function () {
  66711. if (!this._isDirty) {
  66712. return;
  66713. }
  66714. if (this.needInitialSkinMatrix) {
  66715. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  66716. var mesh = this._meshesWithPoseMatrix[index];
  66717. var poseMatrix = mesh.getPoseMatrix();
  66718. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  66719. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66720. }
  66721. if (this._synchronizedWithMesh !== mesh) {
  66722. this._synchronizedWithMesh = mesh;
  66723. // Prepare bones
  66724. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  66725. var bone = this.bones[boneIndex];
  66726. if (!bone.getParent()) {
  66727. var matrix = bone.getBaseMatrix();
  66728. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  66729. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  66730. }
  66731. }
  66732. }
  66733. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  66734. }
  66735. }
  66736. else {
  66737. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  66738. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66739. }
  66740. this._computeTransformMatrices(this._transformMatrices, null);
  66741. }
  66742. this._isDirty = false;
  66743. this._scene._activeBones.addCount(this.bones.length, false);
  66744. };
  66745. Skeleton.prototype.getAnimatables = function () {
  66746. if (!this._animatables || this._animatables.length !== this.bones.length) {
  66747. this._animatables = [];
  66748. for (var index = 0; index < this.bones.length; index++) {
  66749. this._animatables.push(this.bones[index]);
  66750. }
  66751. }
  66752. return this._animatables;
  66753. };
  66754. Skeleton.prototype.clone = function (name, id) {
  66755. var result = new Skeleton(name, id || name, this._scene);
  66756. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66757. for (var index = 0; index < this.bones.length; index++) {
  66758. var source = this.bones[index];
  66759. var parentBone = null;
  66760. var parent_1 = source.getParent();
  66761. if (parent_1) {
  66762. var parentIndex = this.bones.indexOf(parent_1);
  66763. parentBone = result.bones[parentIndex];
  66764. }
  66765. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  66766. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  66767. }
  66768. if (this._ranges) {
  66769. result._ranges = {};
  66770. for (var rangeName in this._ranges) {
  66771. var range = this._ranges[rangeName];
  66772. if (range) {
  66773. result._ranges[rangeName] = range.clone();
  66774. }
  66775. }
  66776. }
  66777. this._isDirty = true;
  66778. return result;
  66779. };
  66780. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  66781. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  66782. this.bones.forEach(function (bone) {
  66783. bone.animations.forEach(function (animation) {
  66784. animation.enableBlending = true;
  66785. animation.blendingSpeed = blendingSpeed;
  66786. });
  66787. });
  66788. };
  66789. Skeleton.prototype.dispose = function () {
  66790. this._meshesWithPoseMatrix = [];
  66791. // Animations
  66792. this.getScene().stopAnimation(this);
  66793. // Remove from scene
  66794. this.getScene().removeSkeleton(this);
  66795. };
  66796. Skeleton.prototype.serialize = function () {
  66797. var serializationObject = {};
  66798. serializationObject.name = this.name;
  66799. serializationObject.id = this.id;
  66800. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  66801. serializationObject.bones = [];
  66802. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66803. for (var index = 0; index < this.bones.length; index++) {
  66804. var bone = this.bones[index];
  66805. var parent_2 = bone.getParent();
  66806. var serializedBone = {
  66807. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  66808. name: bone.name,
  66809. matrix: bone.getBaseMatrix().toArray(),
  66810. rest: bone.getRestPose().toArray()
  66811. };
  66812. serializationObject.bones.push(serializedBone);
  66813. if (bone.length) {
  66814. serializedBone.length = bone.length;
  66815. }
  66816. if (bone.animations && bone.animations.length > 0) {
  66817. serializedBone.animation = bone.animations[0].serialize();
  66818. }
  66819. serializationObject.ranges = [];
  66820. for (var name in this._ranges) {
  66821. var source = this._ranges[name];
  66822. if (!source) {
  66823. continue;
  66824. }
  66825. var range = {};
  66826. range.name = name;
  66827. range.from = source.from;
  66828. range.to = source.to;
  66829. serializationObject.ranges.push(range);
  66830. }
  66831. }
  66832. return serializationObject;
  66833. };
  66834. Skeleton.Parse = function (parsedSkeleton, scene) {
  66835. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  66836. if (parsedSkeleton.dimensionsAtRest) {
  66837. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  66838. }
  66839. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  66840. var index;
  66841. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  66842. var parsedBone = parsedSkeleton.bones[index];
  66843. var parentBone = null;
  66844. if (parsedBone.parentBoneIndex > -1) {
  66845. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  66846. }
  66847. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  66848. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  66849. if (parsedBone.length) {
  66850. bone.length = parsedBone.length;
  66851. }
  66852. if (parsedBone.animation) {
  66853. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  66854. }
  66855. }
  66856. // placed after bones, so createAnimationRange can cascade down
  66857. if (parsedSkeleton.ranges) {
  66858. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  66859. var data = parsedSkeleton.ranges[index];
  66860. skeleton.createAnimationRange(data.name, data.from, data.to);
  66861. }
  66862. }
  66863. return skeleton;
  66864. };
  66865. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  66866. if (forceUpdate === void 0) { forceUpdate = false; }
  66867. var renderId = this._scene.getRenderId();
  66868. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  66869. this.bones[0].computeAbsoluteTransforms();
  66870. this._lastAbsoluteTransformsUpdateId = renderId;
  66871. }
  66872. };
  66873. Skeleton.prototype.getPoseMatrix = function () {
  66874. var poseMatrix = null;
  66875. if (this._meshesWithPoseMatrix.length > 0) {
  66876. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  66877. }
  66878. return poseMatrix;
  66879. };
  66880. Skeleton.prototype.sortBones = function () {
  66881. var bones = new Array();
  66882. var visited = new Array(this.bones.length);
  66883. for (var index = 0; index < this.bones.length; index++) {
  66884. this._sortBones(index, bones, visited);
  66885. }
  66886. this.bones = bones;
  66887. };
  66888. Skeleton.prototype._sortBones = function (index, bones, visited) {
  66889. if (visited[index]) {
  66890. return;
  66891. }
  66892. visited[index] = true;
  66893. var bone = this.bones[index];
  66894. if (bone._index === undefined) {
  66895. bone._index = index;
  66896. }
  66897. var parentBone = bone.getParent();
  66898. if (parentBone) {
  66899. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  66900. }
  66901. bones.push(bone);
  66902. };
  66903. return Skeleton;
  66904. }());
  66905. BABYLON.Skeleton = Skeleton;
  66906. })(BABYLON || (BABYLON = {}));
  66907. //# sourceMappingURL=babylon.skeleton.js.map
  66908. var BABYLON;
  66909. (function (BABYLON) {
  66910. var SphericalPolynomial = /** @class */ (function () {
  66911. function SphericalPolynomial() {
  66912. this.x = BABYLON.Vector3.Zero();
  66913. this.y = BABYLON.Vector3.Zero();
  66914. this.z = BABYLON.Vector3.Zero();
  66915. this.xx = BABYLON.Vector3.Zero();
  66916. this.yy = BABYLON.Vector3.Zero();
  66917. this.zz = BABYLON.Vector3.Zero();
  66918. this.xy = BABYLON.Vector3.Zero();
  66919. this.yz = BABYLON.Vector3.Zero();
  66920. this.zx = BABYLON.Vector3.Zero();
  66921. }
  66922. SphericalPolynomial.prototype.addAmbient = function (color) {
  66923. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66924. this.xx = this.xx.add(colorVector);
  66925. this.yy = this.yy.add(colorVector);
  66926. this.zz = this.zz.add(colorVector);
  66927. };
  66928. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  66929. var result = new SphericalPolynomial();
  66930. result.x = harmonics.L11.scale(1.02333);
  66931. result.y = harmonics.L1_1.scale(1.02333);
  66932. result.z = harmonics.L10.scale(1.02333);
  66933. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  66934. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  66935. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  66936. result.yz = harmonics.L2_1.scale(0.858086);
  66937. result.zx = harmonics.L21.scale(0.858086);
  66938. result.xy = harmonics.L2_2.scale(0.858086);
  66939. result.scale(1.0 / Math.PI);
  66940. return result;
  66941. };
  66942. SphericalPolynomial.prototype.scale = function (scale) {
  66943. this.x = this.x.scale(scale);
  66944. this.y = this.y.scale(scale);
  66945. this.z = this.z.scale(scale);
  66946. this.xx = this.xx.scale(scale);
  66947. this.yy = this.yy.scale(scale);
  66948. this.zz = this.zz.scale(scale);
  66949. this.yz = this.yz.scale(scale);
  66950. this.zx = this.zx.scale(scale);
  66951. this.xy = this.xy.scale(scale);
  66952. };
  66953. return SphericalPolynomial;
  66954. }());
  66955. BABYLON.SphericalPolynomial = SphericalPolynomial;
  66956. var SphericalHarmonics = /** @class */ (function () {
  66957. function SphericalHarmonics() {
  66958. this.L00 = BABYLON.Vector3.Zero();
  66959. this.L1_1 = BABYLON.Vector3.Zero();
  66960. this.L10 = BABYLON.Vector3.Zero();
  66961. this.L11 = BABYLON.Vector3.Zero();
  66962. this.L2_2 = BABYLON.Vector3.Zero();
  66963. this.L2_1 = BABYLON.Vector3.Zero();
  66964. this.L20 = BABYLON.Vector3.Zero();
  66965. this.L21 = BABYLON.Vector3.Zero();
  66966. this.L22 = BABYLON.Vector3.Zero();
  66967. }
  66968. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  66969. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66970. var c = colorVector.scale(deltaSolidAngle);
  66971. this.L00 = this.L00.add(c.scale(0.282095));
  66972. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  66973. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  66974. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  66975. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  66976. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  66977. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  66978. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  66979. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  66980. };
  66981. SphericalHarmonics.prototype.scale = function (scale) {
  66982. this.L00 = this.L00.scale(scale);
  66983. this.L1_1 = this.L1_1.scale(scale);
  66984. this.L10 = this.L10.scale(scale);
  66985. this.L11 = this.L11.scale(scale);
  66986. this.L2_2 = this.L2_2.scale(scale);
  66987. this.L2_1 = this.L2_1.scale(scale);
  66988. this.L20 = this.L20.scale(scale);
  66989. this.L21 = this.L21.scale(scale);
  66990. this.L22 = this.L22.scale(scale);
  66991. };
  66992. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  66993. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  66994. //
  66995. // E_lm = A_l * L_lm
  66996. //
  66997. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  66998. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  66999. // the scaling factors are given in equation 9.
  67000. // Constant (Band 0)
  67001. this.L00 = this.L00.scale(3.141593);
  67002. // Linear (Band 1)
  67003. this.L1_1 = this.L1_1.scale(2.094395);
  67004. this.L10 = this.L10.scale(2.094395);
  67005. this.L11 = this.L11.scale(2.094395);
  67006. // Quadratic (Band 2)
  67007. this.L2_2 = this.L2_2.scale(0.785398);
  67008. this.L2_1 = this.L2_1.scale(0.785398);
  67009. this.L20 = this.L20.scale(0.785398);
  67010. this.L21 = this.L21.scale(0.785398);
  67011. this.L22 = this.L22.scale(0.785398);
  67012. };
  67013. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  67014. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  67015. // L = (1/pi) * E * rho
  67016. //
  67017. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  67018. this.scale(1.0 / Math.PI);
  67019. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  67020. // (The pixel shader must apply albedo after texture fetches, etc).
  67021. };
  67022. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  67023. var result = new SphericalHarmonics();
  67024. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  67025. result.L1_1 = polynomial.y.scale(0.977204);
  67026. result.L10 = polynomial.z.scale(0.977204);
  67027. result.L11 = polynomial.x.scale(0.977204);
  67028. result.L2_2 = polynomial.xy.scale(1.16538);
  67029. result.L2_1 = polynomial.yz.scale(1.16538);
  67030. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  67031. result.L21 = polynomial.zx.scale(1.16538);
  67032. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  67033. result.scale(Math.PI);
  67034. return result;
  67035. };
  67036. return SphericalHarmonics;
  67037. }());
  67038. BABYLON.SphericalHarmonics = SphericalHarmonics;
  67039. })(BABYLON || (BABYLON = {}));
  67040. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  67041. var BABYLON;
  67042. (function (BABYLON) {
  67043. var FileFaceOrientation = /** @class */ (function () {
  67044. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  67045. this.name = name;
  67046. this.worldAxisForNormal = worldAxisForNormal;
  67047. this.worldAxisForFileX = worldAxisForFileX;
  67048. this.worldAxisForFileY = worldAxisForFileY;
  67049. }
  67050. return FileFaceOrientation;
  67051. }());
  67052. ;
  67053. /**
  67054. * Helper class dealing with the extraction of spherical polynomial dataArray
  67055. * from a cube map.
  67056. */
  67057. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  67058. function CubeMapToSphericalPolynomialTools() {
  67059. }
  67060. /**
  67061. * Converts a texture to the according Spherical Polynomial data.
  67062. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67063. *
  67064. * @param texture The texture to extract the information from.
  67065. * @return The Spherical Polynomial data.
  67066. */
  67067. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  67068. if (!texture.isCube) {
  67069. // Only supports cube Textures currently.
  67070. return null;
  67071. }
  67072. var size = texture.getSize().width;
  67073. var right = texture.readPixels(0);
  67074. var left = texture.readPixels(1);
  67075. var up;
  67076. var down;
  67077. if (texture.isRenderTarget) {
  67078. up = texture.readPixels(3);
  67079. down = texture.readPixels(2);
  67080. }
  67081. else {
  67082. up = texture.readPixels(2);
  67083. down = texture.readPixels(3);
  67084. }
  67085. var front = texture.readPixels(4);
  67086. var back = texture.readPixels(5);
  67087. var gammaSpace = texture.gammaSpace;
  67088. // Always read as RGBA.
  67089. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  67090. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67091. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67092. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67093. }
  67094. var cubeInfo = {
  67095. size: size,
  67096. right: right,
  67097. left: left,
  67098. up: up,
  67099. down: down,
  67100. front: front,
  67101. back: back,
  67102. format: format,
  67103. type: type,
  67104. gammaSpace: gammaSpace,
  67105. };
  67106. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  67107. };
  67108. /**
  67109. * Converts a cubemap to the according Spherical Polynomial data.
  67110. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67111. *
  67112. * @param cubeInfo The Cube map to extract the information from.
  67113. * @return The Spherical Polynomial data.
  67114. */
  67115. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  67116. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  67117. var totalSolidAngle = 0.0;
  67118. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  67119. var du = 2.0 / cubeInfo.size;
  67120. var dv = du;
  67121. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  67122. var minUV = du * 0.5 - 1.0;
  67123. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67124. var fileFace = this.FileFaces[faceIndex];
  67125. var dataArray = cubeInfo[fileFace.name];
  67126. var v = minUV;
  67127. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  67128. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  67129. // Because SP is still linear, so summation is fine in that basis.
  67130. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  67131. for (var y = 0; y < cubeInfo.size; y++) {
  67132. var u = minUV;
  67133. for (var x = 0; x < cubeInfo.size; x++) {
  67134. // World direction (not normalised)
  67135. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  67136. worldDirection.normalize();
  67137. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  67138. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  67139. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  67140. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  67141. // Handle Integer types.
  67142. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67143. r /= 255;
  67144. g /= 255;
  67145. b /= 255;
  67146. }
  67147. // Handle Gamma space textures.
  67148. if (cubeInfo.gammaSpace) {
  67149. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  67150. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  67151. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  67152. }
  67153. var color = new BABYLON.Color3(r, g, b);
  67154. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  67155. totalSolidAngle += deltaSolidAngle;
  67156. u += du;
  67157. }
  67158. v += dv;
  67159. }
  67160. }
  67161. // Solid angle for entire sphere is 4*pi
  67162. var sphereSolidAngle = 4.0 * Math.PI;
  67163. // Adjust the solid angle to allow for how many faces we processed.
  67164. var facesProcessed = 6.0;
  67165. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  67166. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  67167. // This is needed because the numerical integration over the cube uses a
  67168. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  67169. // and also to compensate for accumulative error due to float precision in the summation.
  67170. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  67171. sphericalHarmonics.scale(correctionFactor);
  67172. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  67173. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  67174. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  67175. };
  67176. CubeMapToSphericalPolynomialTools.FileFaces = [
  67177. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67178. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67179. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67180. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67181. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67182. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67183. ];
  67184. return CubeMapToSphericalPolynomialTools;
  67185. }());
  67186. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67187. })(BABYLON || (BABYLON = {}));
  67188. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67189. var BABYLON;
  67190. (function (BABYLON) {
  67191. /**
  67192. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67193. */
  67194. var PanoramaToCubeMapTools = /** @class */ (function () {
  67195. function PanoramaToCubeMapTools() {
  67196. }
  67197. /**
  67198. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67199. *
  67200. * @param float32Array The source data.
  67201. * @param inputWidth The width of the input panorama.
  67202. * @param inputhHeight The height of the input panorama.
  67203. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67204. * @return The cubemap data
  67205. */
  67206. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67207. if (!float32Array) {
  67208. throw "ConvertPanoramaToCubemap: input cannot be null";
  67209. }
  67210. if (float32Array.length != inputWidth * inputHeight * 3) {
  67211. throw "ConvertPanoramaToCubemap: input size is wrong";
  67212. }
  67213. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67214. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67215. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67216. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67217. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67218. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67219. return {
  67220. front: textureFront,
  67221. back: textureBack,
  67222. left: textureLeft,
  67223. right: textureRight,
  67224. up: textureUp,
  67225. down: textureDown,
  67226. size: size,
  67227. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67228. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67229. gammaSpace: false,
  67230. };
  67231. };
  67232. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67233. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67234. var textureArray = new Float32Array(buffer);
  67235. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67236. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67237. var dy = 1 / texSize;
  67238. var fy = 0;
  67239. for (var y = 0; y < texSize; y++) {
  67240. var xv1 = faceData[0];
  67241. var xv2 = faceData[2];
  67242. for (var x = 0; x < texSize; x++) {
  67243. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67244. v.normalize();
  67245. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67246. // 3 channels per pixels
  67247. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67248. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67249. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67250. xv1 = xv1.add(rotDX1);
  67251. xv2 = xv2.add(rotDX2);
  67252. }
  67253. fy += dy;
  67254. }
  67255. return textureArray;
  67256. };
  67257. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67258. var theta = Math.atan2(vDir.z, vDir.x);
  67259. var phi = Math.acos(vDir.y);
  67260. while (theta < -Math.PI)
  67261. theta += 2 * Math.PI;
  67262. while (theta > Math.PI)
  67263. theta -= 2 * Math.PI;
  67264. var dx = theta / Math.PI;
  67265. var dy = phi / Math.PI;
  67266. // recenter.
  67267. dx = dx * 0.5 + 0.5;
  67268. var px = Math.round(dx * inputWidth);
  67269. if (px < 0)
  67270. px = 0;
  67271. else if (px >= inputWidth)
  67272. px = inputWidth - 1;
  67273. var py = Math.round(dy * inputHeight);
  67274. if (py < 0)
  67275. py = 0;
  67276. else if (py >= inputHeight)
  67277. py = inputHeight - 1;
  67278. var inputY = (inputHeight - py - 1);
  67279. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67280. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67281. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67282. return {
  67283. r: r,
  67284. g: g,
  67285. b: b
  67286. };
  67287. };
  67288. PanoramaToCubeMapTools.FACE_FRONT = [
  67289. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67290. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67291. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67292. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67293. ];
  67294. PanoramaToCubeMapTools.FACE_BACK = [
  67295. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67296. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67297. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67298. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67299. ];
  67300. PanoramaToCubeMapTools.FACE_RIGHT = [
  67301. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67302. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67303. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67304. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67305. ];
  67306. PanoramaToCubeMapTools.FACE_LEFT = [
  67307. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67308. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67309. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67310. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67311. ];
  67312. PanoramaToCubeMapTools.FACE_DOWN = [
  67313. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67314. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67315. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67316. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67317. ];
  67318. PanoramaToCubeMapTools.FACE_UP = [
  67319. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67320. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67321. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67322. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67323. ];
  67324. return PanoramaToCubeMapTools;
  67325. }());
  67326. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67327. })(BABYLON || (BABYLON = {}));
  67328. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67329. var BABYLON;
  67330. (function (BABYLON) {
  67331. ;
  67332. /**
  67333. * This groups tools to convert HDR texture to native colors array.
  67334. */
  67335. var HDRTools = /** @class */ (function () {
  67336. function HDRTools() {
  67337. }
  67338. HDRTools.Ldexp = function (mantissa, exponent) {
  67339. if (exponent > 1023) {
  67340. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67341. }
  67342. if (exponent < -1074) {
  67343. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67344. }
  67345. return mantissa * Math.pow(2, exponent);
  67346. };
  67347. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67348. if (exponent > 0) {
  67349. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67350. float32array[index + 0] = red * exponent;
  67351. float32array[index + 1] = green * exponent;
  67352. float32array[index + 2] = blue * exponent;
  67353. }
  67354. else {
  67355. float32array[index + 0] = 0;
  67356. float32array[index + 1] = 0;
  67357. float32array[index + 2] = 0;
  67358. }
  67359. };
  67360. HDRTools.readStringLine = function (uint8array, startIndex) {
  67361. var line = "";
  67362. var character = "";
  67363. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67364. character = String.fromCharCode(uint8array[i]);
  67365. if (character == "\n") {
  67366. break;
  67367. }
  67368. line += character;
  67369. }
  67370. return line;
  67371. };
  67372. /**
  67373. * Reads header information from an RGBE texture stored in a native array.
  67374. * More information on this format are available here:
  67375. * https://en.wikipedia.org/wiki/RGBE_image_format
  67376. *
  67377. * @param uint8array The binary file stored in native array.
  67378. * @return The header information.
  67379. */
  67380. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67381. var height = 0;
  67382. var width = 0;
  67383. var line = this.readStringLine(uint8array, 0);
  67384. if (line[0] != '#' || line[1] != '?') {
  67385. throw "Bad HDR Format.";
  67386. }
  67387. var endOfHeader = false;
  67388. var findFormat = false;
  67389. var lineIndex = 0;
  67390. do {
  67391. lineIndex += (line.length + 1);
  67392. line = this.readStringLine(uint8array, lineIndex);
  67393. if (line == "FORMAT=32-bit_rle_rgbe") {
  67394. findFormat = true;
  67395. }
  67396. else if (line.length == 0) {
  67397. endOfHeader = true;
  67398. }
  67399. } while (!endOfHeader);
  67400. if (!findFormat) {
  67401. throw "HDR Bad header format, unsupported FORMAT";
  67402. }
  67403. lineIndex += (line.length + 1);
  67404. line = this.readStringLine(uint8array, lineIndex);
  67405. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67406. var match = sizeRegexp.exec(line);
  67407. // TODO. Support +Y and -X if needed.
  67408. if (!match || match.length < 3) {
  67409. throw "HDR Bad header format, no size";
  67410. }
  67411. width = parseInt(match[2]);
  67412. height = parseInt(match[1]);
  67413. if (width < 8 || width > 0x7fff) {
  67414. throw "HDR Bad header format, unsupported size";
  67415. }
  67416. lineIndex += (line.length + 1);
  67417. return {
  67418. height: height,
  67419. width: width,
  67420. dataPosition: lineIndex
  67421. };
  67422. };
  67423. /**
  67424. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  67425. * This RGBE texture needs to store the information as a panorama.
  67426. *
  67427. * More information on this format are available here:
  67428. * https://en.wikipedia.org/wiki/RGBE_image_format
  67429. *
  67430. * @param buffer The binary file stored in an array buffer.
  67431. * @param size The expected size of the extracted cubemap.
  67432. * @return The Cube Map information.
  67433. */
  67434. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  67435. var uint8array = new Uint8Array(buffer);
  67436. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  67437. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67438. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  67439. return cubeMapData;
  67440. };
  67441. /**
  67442. * Returns the pixels data extracted from an RGBE texture.
  67443. * This pixels will be stored left to right up to down in the R G B order in one array.
  67444. *
  67445. * More information on this format are available here:
  67446. * https://en.wikipedia.org/wiki/RGBE_image_format
  67447. *
  67448. * @param uint8array The binary file stored in an array buffer.
  67449. * @param hdrInfo The header information of the file.
  67450. * @return The pixels data in RGB right to left up to down order.
  67451. */
  67452. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  67453. // Keep for multi format supports.
  67454. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67455. };
  67456. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  67457. var num_scanlines = hdrInfo.height;
  67458. var scanline_width = hdrInfo.width;
  67459. var a, b, c, d, count;
  67460. var dataIndex = hdrInfo.dataPosition;
  67461. var index = 0, endIndex = 0, i = 0;
  67462. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  67463. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  67464. // 3 channels of 4 bytes per pixel in float.
  67465. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  67466. var resultArray = new Float32Array(resultBuffer);
  67467. // read in each successive scanline
  67468. while (num_scanlines > 0) {
  67469. a = uint8array[dataIndex++];
  67470. b = uint8array[dataIndex++];
  67471. c = uint8array[dataIndex++];
  67472. d = uint8array[dataIndex++];
  67473. if (a != 2 || b != 2 || (c & 0x80)) {
  67474. // this file is not run length encoded
  67475. throw "HDR Bad header format, not RLE";
  67476. }
  67477. if (((c << 8) | d) != scanline_width) {
  67478. throw "HDR Bad header format, wrong scan line width";
  67479. }
  67480. index = 0;
  67481. // read each of the four channels for the scanline into the buffer
  67482. for (i = 0; i < 4; i++) {
  67483. endIndex = (i + 1) * scanline_width;
  67484. while (index < endIndex) {
  67485. a = uint8array[dataIndex++];
  67486. b = uint8array[dataIndex++];
  67487. if (a > 128) {
  67488. // a run of the same value
  67489. count = a - 128;
  67490. if ((count == 0) || (count > endIndex - index)) {
  67491. throw "HDR Bad Format, bad scanline data (run)";
  67492. }
  67493. while (count-- > 0) {
  67494. scanLineArray[index++] = b;
  67495. }
  67496. }
  67497. else {
  67498. // a non-run
  67499. count = a;
  67500. if ((count == 0) || (count > endIndex - index)) {
  67501. throw "HDR Bad Format, bad scanline data (non-run)";
  67502. }
  67503. scanLineArray[index++] = b;
  67504. if (--count > 0) {
  67505. for (var j = 0; j < count; j++) {
  67506. scanLineArray[index++] = uint8array[dataIndex++];
  67507. }
  67508. }
  67509. }
  67510. }
  67511. }
  67512. // now convert data from buffer into floats
  67513. for (i = 0; i < scanline_width; i++) {
  67514. a = scanLineArray[i];
  67515. b = scanLineArray[i + scanline_width];
  67516. c = scanLineArray[i + 2 * scanline_width];
  67517. d = scanLineArray[i + 3 * scanline_width];
  67518. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  67519. }
  67520. num_scanlines--;
  67521. }
  67522. return resultArray;
  67523. };
  67524. return HDRTools;
  67525. }());
  67526. BABYLON.HDRTools = HDRTools;
  67527. })(BABYLON || (BABYLON = {}));
  67528. //# sourceMappingURL=babylon.hdr.js.map
  67529. var BABYLON;
  67530. (function (BABYLON) {
  67531. /**
  67532. * This represents a texture coming from an HDR input.
  67533. *
  67534. * The only supported format is currently panorama picture stored in RGBE format.
  67535. * Example of such files can be found on HDRLib: http://hdrlib.com/
  67536. */
  67537. var HDRCubeTexture = /** @class */ (function (_super) {
  67538. __extends(HDRCubeTexture, _super);
  67539. /**
  67540. * Instantiates an HDRTexture from the following parameters.
  67541. *
  67542. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  67543. * @param scene The scene the texture will be used in
  67544. * @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.
  67545. * @param noMipmap Forces to not generate the mipmap if true
  67546. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  67547. * @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)
  67548. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  67549. */
  67550. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  67551. if (noMipmap === void 0) { noMipmap = false; }
  67552. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67553. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67554. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67555. if (onLoad === void 0) { onLoad = null; }
  67556. if (onError === void 0) { onError = null; }
  67557. var _this = _super.call(this, scene) || this;
  67558. _this._useInGammaSpace = false;
  67559. _this._generateHarmonics = true;
  67560. _this._isBABYLONPreprocessed = false;
  67561. _this._onLoad = null;
  67562. _this._onError = null;
  67563. /**
  67564. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  67565. */
  67566. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67567. /**
  67568. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  67569. * This is usefull at run time to apply the good shader.
  67570. */
  67571. _this.isPMREM = false;
  67572. _this._isBlocking = true;
  67573. if (!url) {
  67574. return _this;
  67575. }
  67576. _this.name = url;
  67577. _this.url = url;
  67578. _this.hasAlpha = false;
  67579. _this.isCube = true;
  67580. _this._textureMatrix = BABYLON.Matrix.Identity();
  67581. _this._onLoad = onLoad;
  67582. _this._onError = onError;
  67583. _this.gammaSpace = false;
  67584. var caps = scene.getEngine().getCaps();
  67585. if (size) {
  67586. _this._isBABYLONPreprocessed = false;
  67587. _this._noMipmap = noMipmap;
  67588. _this._size = size;
  67589. _this._useInGammaSpace = useInGammaSpace;
  67590. _this._usePMREMGenerator = usePMREMGenerator &&
  67591. caps.textureLOD &&
  67592. caps.textureFloat &&
  67593. !_this._useInGammaSpace;
  67594. }
  67595. else {
  67596. _this._isBABYLONPreprocessed = true;
  67597. _this._noMipmap = false;
  67598. _this._useInGammaSpace = false;
  67599. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  67600. !_this._useInGammaSpace;
  67601. }
  67602. _this.isPMREM = _this._usePMREMGenerator;
  67603. _this._texture = _this._getFromCache(url, _this._noMipmap);
  67604. if (!_this._texture) {
  67605. if (!scene.useDelayedTextureLoading) {
  67606. _this.loadTexture();
  67607. }
  67608. else {
  67609. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67610. }
  67611. }
  67612. return _this;
  67613. }
  67614. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  67615. /**
  67616. * Gets wether or not the texture is blocking during loading.
  67617. */
  67618. get: function () {
  67619. return this._isBlocking;
  67620. },
  67621. /**
  67622. * Sets wether or not the texture is blocking during loading.
  67623. */
  67624. set: function (value) {
  67625. this._isBlocking = value;
  67626. },
  67627. enumerable: true,
  67628. configurable: true
  67629. });
  67630. /**
  67631. * Occurs when the file is a preprocessed .babylon.hdr file.
  67632. */
  67633. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  67634. var _this = this;
  67635. var mipLevels = 0;
  67636. var floatArrayView = null;
  67637. var scene = this.getScene();
  67638. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  67639. var mips = new Array();
  67640. if (!floatArrayView) {
  67641. return mips;
  67642. }
  67643. var startIndex = 30;
  67644. for (var level = 0; level < mipLevels; level++) {
  67645. mips.push([]);
  67646. // Fill each pixel of the mip level.
  67647. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  67648. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67649. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  67650. mips[level].push(faceData);
  67651. startIndex += faceSize;
  67652. }
  67653. }
  67654. return mips;
  67655. } : null;
  67656. var callback = function (buffer) {
  67657. var scene = _this.getScene();
  67658. if (!scene) {
  67659. return null;
  67660. }
  67661. // Create Native Array Views
  67662. var intArrayView = new Int32Array(buffer);
  67663. floatArrayView = new Float32Array(buffer);
  67664. // Fill header.
  67665. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  67666. _this._size = intArrayView[1]; // CubeMap max mip face size.
  67667. // Update Texture Information.
  67668. if (!_this._texture) {
  67669. return null;
  67670. }
  67671. _this._texture.updateSize(_this._size, _this._size);
  67672. // Fill polynomial information.
  67673. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  67674. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  67675. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  67676. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  67677. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  67678. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  67679. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  67680. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  67681. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  67682. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  67683. _this.sphericalPolynomial = sphericalPolynomial;
  67684. // Fill pixel data.
  67685. mipLevels = intArrayView[29]; // Number of mip levels.
  67686. var startIndex = 30;
  67687. var data = [];
  67688. var faceSize = Math.pow(_this._size, 2) * 3;
  67689. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67690. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  67691. startIndex += faceSize;
  67692. }
  67693. var results = [];
  67694. var byteArray = null;
  67695. // Push each faces.
  67696. for (var k = 0; k < 6; k++) {
  67697. var dataFace = null;
  67698. // To be deprecated.
  67699. if (version === 1) {
  67700. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  67701. dataFace = data[j];
  67702. }
  67703. // If special cases.
  67704. if (!mipmapGenerator && dataFace) {
  67705. if (!scene.getEngine().getCaps().textureFloat) {
  67706. // 3 channels of 1 bytes per pixel in bytes.
  67707. var byteBuffer = new ArrayBuffer(faceSize);
  67708. byteArray = new Uint8Array(byteBuffer);
  67709. }
  67710. for (var i = 0; i < _this._size * _this._size; i++) {
  67711. // Put in gamma space if requested.
  67712. if (_this._useInGammaSpace) {
  67713. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67714. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67715. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67716. }
  67717. // Convert to int texture for fallback.
  67718. if (byteArray) {
  67719. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67720. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67721. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67722. // May use luminance instead if the result is not accurate.
  67723. var max = Math.max(Math.max(r, g), b);
  67724. if (max > 255) {
  67725. var scale = 255 / max;
  67726. r *= scale;
  67727. g *= scale;
  67728. b *= scale;
  67729. }
  67730. byteArray[(i * 3) + 0] = r;
  67731. byteArray[(i * 3) + 1] = g;
  67732. byteArray[(i * 3) + 2] = b;
  67733. }
  67734. }
  67735. }
  67736. // Fill the array accordingly.
  67737. if (byteArray) {
  67738. results.push(byteArray);
  67739. }
  67740. else {
  67741. results.push(dataFace);
  67742. }
  67743. }
  67744. return results;
  67745. };
  67746. if (scene) {
  67747. 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);
  67748. }
  67749. };
  67750. /**
  67751. * Occurs when the file is raw .hdr file.
  67752. */
  67753. HDRCubeTexture.prototype.loadHDRTexture = function () {
  67754. var _this = this;
  67755. var callback = function (buffer) {
  67756. var scene = _this.getScene();
  67757. if (!scene) {
  67758. return null;
  67759. }
  67760. // Extract the raw linear data.
  67761. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  67762. // Generate harmonics if needed.
  67763. if (_this._generateHarmonics) {
  67764. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  67765. _this.sphericalPolynomial = sphericalPolynomial;
  67766. }
  67767. var results = [];
  67768. var byteArray = null;
  67769. // Push each faces.
  67770. for (var j = 0; j < 6; j++) {
  67771. // Create uintarray fallback.
  67772. if (!scene.getEngine().getCaps().textureFloat) {
  67773. // 3 channels of 1 bytes per pixel in bytes.
  67774. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  67775. byteArray = new Uint8Array(byteBuffer);
  67776. }
  67777. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  67778. // If special cases.
  67779. if (_this._useInGammaSpace || byteArray) {
  67780. for (var i = 0; i < _this._size * _this._size; i++) {
  67781. // Put in gamma space if requested.
  67782. if (_this._useInGammaSpace) {
  67783. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67784. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67785. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67786. }
  67787. // Convert to int texture for fallback.
  67788. if (byteArray) {
  67789. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67790. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67791. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67792. // May use luminance instead if the result is not accurate.
  67793. var max = Math.max(Math.max(r, g), b);
  67794. if (max > 255) {
  67795. var scale = 255 / max;
  67796. r *= scale;
  67797. g *= scale;
  67798. b *= scale;
  67799. }
  67800. byteArray[(i * 3) + 0] = r;
  67801. byteArray[(i * 3) + 1] = g;
  67802. byteArray[(i * 3) + 2] = b;
  67803. }
  67804. }
  67805. }
  67806. if (byteArray) {
  67807. results.push(byteArray);
  67808. }
  67809. else {
  67810. results.push(dataFace);
  67811. }
  67812. }
  67813. return results;
  67814. };
  67815. var mipmapGenerator = null;
  67816. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  67817. // if (!this._noMipmap &&
  67818. // this._usePMREMGenerator) {
  67819. // mipmapGenerator = (data: ArrayBufferView[]) => {
  67820. // // Custom setup of the generator matching with the PBR shader values.
  67821. // var generator = new BABYLON.PMREMGenerator(data,
  67822. // this._size,
  67823. // this._size,
  67824. // 0,
  67825. // 3,
  67826. // this.getScene().getEngine().getCaps().textureFloat,
  67827. // 2048,
  67828. // 0.25,
  67829. // false,
  67830. // true);
  67831. // return generator.filterCubeMap();
  67832. // };
  67833. // }
  67834. var scene = this.getScene();
  67835. if (scene) {
  67836. 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);
  67837. }
  67838. };
  67839. /**
  67840. * Starts the loading process of the texture.
  67841. */
  67842. HDRCubeTexture.prototype.loadTexture = function () {
  67843. if (this._isBABYLONPreprocessed) {
  67844. this.loadBabylonTexture();
  67845. }
  67846. else {
  67847. this.loadHDRTexture();
  67848. }
  67849. };
  67850. HDRCubeTexture.prototype.clone = function () {
  67851. var scene = this.getScene();
  67852. if (!scene) {
  67853. return this;
  67854. }
  67855. var size = (this._isBABYLONPreprocessed ? null : this._size);
  67856. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  67857. // Base texture
  67858. newTexture.level = this.level;
  67859. newTexture.wrapU = this.wrapU;
  67860. newTexture.wrapV = this.wrapV;
  67861. newTexture.coordinatesIndex = this.coordinatesIndex;
  67862. newTexture.coordinatesMode = this.coordinatesMode;
  67863. return newTexture;
  67864. };
  67865. // Methods
  67866. HDRCubeTexture.prototype.delayLoad = function () {
  67867. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67868. return;
  67869. }
  67870. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67871. this._texture = this._getFromCache(this.url, this._noMipmap);
  67872. if (!this._texture) {
  67873. this.loadTexture();
  67874. }
  67875. };
  67876. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  67877. return this._textureMatrix;
  67878. };
  67879. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67880. this._textureMatrix = value;
  67881. };
  67882. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67883. var texture = null;
  67884. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  67885. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  67886. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  67887. texture.name = parsedTexture.name;
  67888. texture.hasAlpha = parsedTexture.hasAlpha;
  67889. texture.level = parsedTexture.level;
  67890. texture.coordinatesMode = parsedTexture.coordinatesMode;
  67891. texture.isBlocking = parsedTexture.isBlocking;
  67892. }
  67893. return texture;
  67894. };
  67895. HDRCubeTexture.prototype.serialize = function () {
  67896. if (!this.name) {
  67897. return null;
  67898. }
  67899. var serializationObject = {};
  67900. serializationObject.name = this.name;
  67901. serializationObject.hasAlpha = this.hasAlpha;
  67902. serializationObject.isCube = true;
  67903. serializationObject.level = this.level;
  67904. serializationObject.size = this._size;
  67905. serializationObject.coordinatesMode = this.coordinatesMode;
  67906. serializationObject.useInGammaSpace = this._useInGammaSpace;
  67907. serializationObject.generateHarmonics = this._generateHarmonics;
  67908. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  67909. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  67910. serializationObject.customType = "BABYLON.HDRCubeTexture";
  67911. serializationObject.noMipmap = this._noMipmap;
  67912. serializationObject.isBlocking = this._isBlocking;
  67913. return serializationObject;
  67914. };
  67915. /**
  67916. * Saves as a file the data contained in the texture in a binary format.
  67917. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67918. * as the spherical used in the lighting.
  67919. * @param url The HDR file url.
  67920. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67921. * @param onError Method called if any error happens during download.
  67922. * @return The packed binary data.
  67923. */
  67924. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  67925. if (onError === void 0) { onError = null; }
  67926. var callback = function (buffer) {
  67927. var data = new Blob([buffer], { type: 'application/octet-stream' });
  67928. // Returns a URL you can use as a href.
  67929. var objUrl = window.URL.createObjectURL(data);
  67930. // Simulates a link to it and click to dowload.
  67931. var a = document.createElement("a");
  67932. document.body.appendChild(a);
  67933. a.style.display = "none";
  67934. a.href = objUrl;
  67935. a.download = "envmap.babylon.hdr";
  67936. a.click();
  67937. };
  67938. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  67939. };
  67940. /**
  67941. * Serializes the data contained in the texture in a binary format.
  67942. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67943. * as the spherical used in the lighting.
  67944. * @param url The HDR file url.
  67945. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67946. * @param onError Method called if any error happens during download.
  67947. * @return The packed binary data.
  67948. */
  67949. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  67950. if (onError === void 0) { onError = null; }
  67951. // Needs the url tho create the texture.
  67952. if (!url) {
  67953. return;
  67954. }
  67955. // Check Power of two size.
  67956. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  67957. return;
  67958. }
  67959. // Coming Back in 3.x.
  67960. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  67961. };
  67962. HDRCubeTexture._facesMapping = [
  67963. "right",
  67964. "left",
  67965. "up",
  67966. "down",
  67967. "front",
  67968. "back"
  67969. ];
  67970. return HDRCubeTexture;
  67971. }(BABYLON.BaseTexture));
  67972. BABYLON.HDRCubeTexture = HDRCubeTexture;
  67973. })(BABYLON || (BABYLON = {}));
  67974. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  67975. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  67976. // Huge respect for a such great lib.
  67977. // Earcut license:
  67978. // Copyright (c) 2016, Mapbox
  67979. //
  67980. // Permission to use, copy, modify, and/or distribute this software for any purpose
  67981. // with or without fee is hereby granted, provided that the above copyright notice
  67982. // and this permission notice appear in all copies.
  67983. //
  67984. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  67985. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  67986. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  67987. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  67988. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  67989. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  67990. // THIS SOFTWARE.
  67991. var Earcut;
  67992. (function (Earcut) {
  67993. /**
  67994. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  67995. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  67996. * @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).
  67997. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  67998. */
  67999. function earcut(data, holeIndices, dim) {
  68000. dim = dim || 2;
  68001. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  68002. if (!outerNode)
  68003. return triangles;
  68004. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  68005. if (hasHoles)
  68006. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  68007. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  68008. if (data.length > 80 * dim) {
  68009. minX = maxX = data[0];
  68010. minY = maxY = data[1];
  68011. for (var i = dim; i < outerLen; i += dim) {
  68012. x = data[i];
  68013. y = data[i + 1];
  68014. if (x < minX)
  68015. minX = x;
  68016. if (y < minY)
  68017. minY = y;
  68018. if (x > maxX)
  68019. maxX = x;
  68020. if (y > maxY)
  68021. maxY = y;
  68022. }
  68023. // minX, minY and size are later used to transform coords into integers for z-order calculation
  68024. size = Math.max(maxX - minX, maxY - minY);
  68025. }
  68026. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  68027. return triangles;
  68028. }
  68029. Earcut.earcut = earcut;
  68030. var Node = /** @class */ (function () {
  68031. function Node(i, x, y) {
  68032. this.i = i;
  68033. this.x = x;
  68034. this.y = y;
  68035. this.prev = null;
  68036. this.next = null;
  68037. this.z = null;
  68038. this.prevZ = null;
  68039. this.nextZ = null;
  68040. this.steiner = false;
  68041. }
  68042. return Node;
  68043. }());
  68044. // create a circular doubly linked list from polygon points in the specified winding order
  68045. function linkedList(data, start, end, dim, clockwise) {
  68046. var i, last = null;
  68047. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  68048. for (i = start; i < end; i += dim)
  68049. last = insertNode(i, data[i], data[i + 1], last);
  68050. }
  68051. else {
  68052. for (i = end - dim; i >= start; i -= dim)
  68053. last = insertNode(i, data[i], data[i + 1], last);
  68054. }
  68055. if (last && equals(last, last.next)) {
  68056. removeNode(last);
  68057. last = last.next;
  68058. }
  68059. return last;
  68060. }
  68061. // eliminate colinear or duplicate points
  68062. function filterPoints(start, end) {
  68063. if (!start)
  68064. return start;
  68065. if (!end)
  68066. end = start;
  68067. var p = start, again;
  68068. do {
  68069. again = false;
  68070. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  68071. removeNode(p);
  68072. p = end = p.prev;
  68073. if (p === p.next)
  68074. return undefined;
  68075. again = true;
  68076. }
  68077. else {
  68078. p = p.next;
  68079. }
  68080. } while (again || p !== end);
  68081. return end;
  68082. }
  68083. // main ear slicing loop which triangulates a polygon (given as a linked list)
  68084. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  68085. if (!ear)
  68086. return;
  68087. // interlink polygon nodes in z-order
  68088. if (!pass && size)
  68089. indexCurve(ear, minX, minY, size);
  68090. var stop = ear, prev, next;
  68091. // iterate through ears, slicing them one by one
  68092. while (ear.prev !== ear.next) {
  68093. prev = ear.prev;
  68094. next = ear.next;
  68095. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  68096. // cut off the triangle
  68097. triangles.push(prev.i / dim);
  68098. triangles.push(ear.i / dim);
  68099. triangles.push(next.i / dim);
  68100. removeNode(ear);
  68101. // skipping the next vertice leads to less sliver triangles
  68102. ear = next.next;
  68103. stop = next.next;
  68104. continue;
  68105. }
  68106. ear = next;
  68107. // if we looped through the whole remaining polygon and can't find any more ears
  68108. if (ear === stop) {
  68109. // try filtering points and slicing again
  68110. if (!pass) {
  68111. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  68112. // if this didn't work, try curing all small self-intersections locally
  68113. }
  68114. else if (pass === 1) {
  68115. ear = cureLocalIntersections(ear, triangles, dim);
  68116. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  68117. // as a last resort, try splitting the remaining polygon into two
  68118. }
  68119. else if (pass === 2) {
  68120. splitEarcut(ear, triangles, dim, minX, minY, size);
  68121. }
  68122. break;
  68123. }
  68124. }
  68125. }
  68126. // check whether a polygon node forms a valid ear with adjacent nodes
  68127. function isEar(ear) {
  68128. var a = ear.prev, b = ear, c = ear.next;
  68129. if (area(a, b, c) >= 0)
  68130. return false; // reflex, can't be an ear
  68131. // now make sure we don't have other points inside the potential ear
  68132. var p = ear.next.next;
  68133. while (p !== ear.prev) {
  68134. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68135. area(p.prev, p, p.next) >= 0)
  68136. return false;
  68137. p = p.next;
  68138. }
  68139. return true;
  68140. }
  68141. function isEarHashed(ear, minX, minY, size) {
  68142. var a = ear.prev, b = ear, c = ear.next;
  68143. if (area(a, b, c) >= 0)
  68144. return false; // reflex, can't be an ear
  68145. // triangle bbox; min & max are calculated like this for speed
  68146. 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);
  68147. // z-order range for the current triangle bbox;
  68148. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  68149. // first look for points inside the triangle in increasing z-order
  68150. var p = ear.nextZ;
  68151. while (p && p.z <= maxZ) {
  68152. if (p !== ear.prev &&
  68153. p !== ear.next &&
  68154. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68155. area(p.prev, p, p.next) >= 0)
  68156. return false;
  68157. p = p.nextZ;
  68158. }
  68159. // then look for points in decreasing z-order
  68160. p = ear.prevZ;
  68161. while (p && p.z >= minZ) {
  68162. if (p !== ear.prev &&
  68163. p !== ear.next &&
  68164. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68165. area(p.prev, p, p.next) >= 0)
  68166. return false;
  68167. p = p.prevZ;
  68168. }
  68169. return true;
  68170. }
  68171. // go through all polygon nodes and cure small local self-intersections
  68172. function cureLocalIntersections(start, triangles, dim) {
  68173. var p = start;
  68174. do {
  68175. var a = p.prev, b = p.next.next;
  68176. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68177. triangles.push(a.i / dim);
  68178. triangles.push(p.i / dim);
  68179. triangles.push(b.i / dim);
  68180. // remove two nodes involved
  68181. removeNode(p);
  68182. removeNode(p.next);
  68183. p = start = b;
  68184. }
  68185. p = p.next;
  68186. } while (p !== start);
  68187. return p;
  68188. }
  68189. // try splitting polygon into two and triangulate them independently
  68190. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68191. // look for a valid diagonal that divides the polygon into two
  68192. var a = start;
  68193. do {
  68194. var b = a.next.next;
  68195. while (b !== a.prev) {
  68196. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68197. // split the polygon in two by the diagonal
  68198. var c = splitPolygon(a, b);
  68199. // filter colinear points around the cuts
  68200. a = filterPoints(a, a.next);
  68201. c = filterPoints(c, c.next);
  68202. // run earcut on each half
  68203. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68204. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68205. return;
  68206. }
  68207. b = b.next;
  68208. }
  68209. a = a.next;
  68210. } while (a !== start);
  68211. }
  68212. // link every hole into the outer loop, producing a single-ring polygon without holes
  68213. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68214. var queue = [], i, len, start, end, list;
  68215. for (i = 0, len = holeIndices.length; i < len; i++) {
  68216. start = holeIndices[i] * dim;
  68217. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68218. list = linkedList(data, start, end, dim, false);
  68219. if (list === list.next)
  68220. list.steiner = true;
  68221. queue.push(getLeftmost(list));
  68222. }
  68223. queue.sort(compareX);
  68224. // process holes from left to right
  68225. for (i = 0; i < queue.length; i++) {
  68226. eliminateHole(queue[i], outerNode);
  68227. outerNode = filterPoints(outerNode, outerNode.next);
  68228. }
  68229. return outerNode;
  68230. }
  68231. function compareX(a, b) {
  68232. return a.x - b.x;
  68233. }
  68234. // find a bridge between vertices that connects hole with an outer ring and and link it
  68235. function eliminateHole(hole, outerNode) {
  68236. outerNode = findHoleBridge(hole, outerNode);
  68237. if (outerNode) {
  68238. var b = splitPolygon(outerNode, hole);
  68239. filterPoints(b, b.next);
  68240. }
  68241. }
  68242. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68243. function findHoleBridge(hole, outerNode) {
  68244. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68245. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68246. // segment's endpoint with lesser x will be potential connection point
  68247. do {
  68248. if (hy <= p.y && hy >= p.next.y) {
  68249. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68250. if (x <= hx && x > qx) {
  68251. qx = x;
  68252. if (x === hx) {
  68253. if (hy === p.y)
  68254. return p;
  68255. if (hy === p.next.y)
  68256. return p.next;
  68257. }
  68258. m = p.x < p.next.x ? p : p.next;
  68259. }
  68260. }
  68261. p = p.next;
  68262. } while (p !== outerNode);
  68263. if (!m)
  68264. return null;
  68265. if (hx === qx)
  68266. return m.prev; // hole touches outer segment; pick lower endpoint
  68267. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68268. // if there are no points found, we have a valid connection;
  68269. // otherwise choose the point of the minimum angle with the ray as connection point
  68270. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68271. p = m.next;
  68272. while (p !== stop) {
  68273. if (hx >= p.x &&
  68274. p.x >= mx &&
  68275. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68276. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68277. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68278. m = p;
  68279. tanMin = tan;
  68280. }
  68281. }
  68282. p = p.next;
  68283. }
  68284. return m;
  68285. }
  68286. // interlink polygon nodes in z-order
  68287. function indexCurve(start, minX, minY, size) {
  68288. var p = start;
  68289. do {
  68290. if (p.z === null)
  68291. p.z = zOrder(p.x, p.y, minX, minY, size);
  68292. p.prevZ = p.prev;
  68293. p.nextZ = p.next;
  68294. p = p.next;
  68295. } while (p !== start);
  68296. p.prevZ.nextZ = null;
  68297. p.prevZ = null;
  68298. sortLinked(p);
  68299. }
  68300. // Simon Tatham's linked list merge sort algorithm
  68301. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68302. function sortLinked(list) {
  68303. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68304. do {
  68305. p = list;
  68306. list = null;
  68307. tail = null;
  68308. numMerges = 0;
  68309. while (p) {
  68310. numMerges++;
  68311. q = p;
  68312. pSize = 0;
  68313. for (i = 0; i < inSize; i++) {
  68314. pSize++;
  68315. q = q.nextZ;
  68316. if (!q)
  68317. break;
  68318. }
  68319. qSize = inSize;
  68320. while (pSize > 0 || (qSize > 0 && q)) {
  68321. if (pSize === 0) {
  68322. e = q;
  68323. q = q.nextZ;
  68324. qSize--;
  68325. }
  68326. else if (qSize === 0 || !q) {
  68327. e = p;
  68328. p = p.nextZ;
  68329. pSize--;
  68330. }
  68331. else if (p.z <= q.z) {
  68332. e = p;
  68333. p = p.nextZ;
  68334. pSize--;
  68335. }
  68336. else {
  68337. e = q;
  68338. q = q.nextZ;
  68339. qSize--;
  68340. }
  68341. if (tail)
  68342. tail.nextZ = e;
  68343. else
  68344. list = e;
  68345. e.prevZ = tail;
  68346. tail = e;
  68347. }
  68348. p = q;
  68349. }
  68350. tail.nextZ = null;
  68351. inSize *= 2;
  68352. } while (numMerges > 1);
  68353. return list;
  68354. }
  68355. // z-order of a point given coords and size of the data bounding box
  68356. function zOrder(x, y, minX, minY, size) {
  68357. // coords are transformed into non-negative 15-bit integer range
  68358. x = 32767 * (x - minX) / size;
  68359. y = 32767 * (y - minY) / size;
  68360. x = (x | (x << 8)) & 0x00FF00FF;
  68361. x = (x | (x << 4)) & 0x0F0F0F0F;
  68362. x = (x | (x << 2)) & 0x33333333;
  68363. x = (x | (x << 1)) & 0x55555555;
  68364. y = (y | (y << 8)) & 0x00FF00FF;
  68365. y = (y | (y << 4)) & 0x0F0F0F0F;
  68366. y = (y | (y << 2)) & 0x33333333;
  68367. y = (y | (y << 1)) & 0x55555555;
  68368. return x | (y << 1);
  68369. }
  68370. // find the leftmost node of a polygon ring
  68371. function getLeftmost(start) {
  68372. var p = start, leftmost = start;
  68373. do {
  68374. if (p.x < leftmost.x)
  68375. leftmost = p;
  68376. p = p.next;
  68377. } while (p !== start);
  68378. return leftmost;
  68379. }
  68380. // check if a point lies within a convex triangle
  68381. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68382. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68383. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68384. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68385. }
  68386. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68387. function isValidDiagonal(a, b) {
  68388. return a.next.i !== b.i &&
  68389. a.prev.i !== b.i &&
  68390. !intersectsPolygon(a, b) &&
  68391. locallyInside(a, b) &&
  68392. locallyInside(b, a) &&
  68393. middleInside(a, b);
  68394. }
  68395. // signed area of a triangle
  68396. function area(p, q, r) {
  68397. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68398. }
  68399. // check if two points are equal
  68400. function equals(p1, p2) {
  68401. return p1.x === p2.x && p1.y === p2.y;
  68402. }
  68403. // check if two segments intersect
  68404. function intersects(p1, q1, p2, q2) {
  68405. if ((equals(p1, q1) && equals(p2, q2)) ||
  68406. (equals(p1, q2) && equals(p2, q1)))
  68407. return true;
  68408. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  68409. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  68410. }
  68411. // check if a polygon diagonal intersects any polygon segments
  68412. function intersectsPolygon(a, b) {
  68413. var p = a;
  68414. do {
  68415. if (p.i !== a.i &&
  68416. p.next.i !== a.i &&
  68417. p.i !== b.i &&
  68418. p.next.i !== b.i &&
  68419. intersects(p, p.next, a, b))
  68420. return true;
  68421. p = p.next;
  68422. } while (p !== a);
  68423. return false;
  68424. }
  68425. // check if a polygon diagonal is locally inside the polygon
  68426. function locallyInside(a, b) {
  68427. return area(a.prev, a, a.next) < 0
  68428. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  68429. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  68430. }
  68431. // check if the middle point of a polygon diagonal is inside the polygon
  68432. function middleInside(a, b) {
  68433. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  68434. do {
  68435. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  68436. inside = !inside;
  68437. p = p.next;
  68438. } while (p !== a);
  68439. return inside;
  68440. }
  68441. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  68442. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  68443. function splitPolygon(a, b) {
  68444. 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;
  68445. a.next = b;
  68446. b.prev = a;
  68447. a2.next = an;
  68448. an.prev = a2;
  68449. b2.next = a2;
  68450. a2.prev = b2;
  68451. bp.next = b2;
  68452. b2.prev = bp;
  68453. return b2;
  68454. }
  68455. // create a node and optionally link it with previous one (in a circular doubly linked list)
  68456. function insertNode(i, x, y, last) {
  68457. var p = new Node(i, x, y);
  68458. if (!last) {
  68459. p.prev = p;
  68460. p.next = p;
  68461. }
  68462. else {
  68463. p.next = last.next;
  68464. p.prev = last;
  68465. last.next.prev = p;
  68466. last.next = p;
  68467. }
  68468. return p;
  68469. }
  68470. function removeNode(p) {
  68471. p.next.prev = p.prev;
  68472. p.prev.next = p.next;
  68473. if (p.prevZ)
  68474. p.prevZ.nextZ = p.nextZ;
  68475. if (p.nextZ)
  68476. p.nextZ.prevZ = p.prevZ;
  68477. }
  68478. /**
  68479. * return a percentage difference between the polygon area and its triangulation area;
  68480. * used to verify correctness of triangulation
  68481. */
  68482. function deviation(data, holeIndices, dim, triangles) {
  68483. var hasHoles = holeIndices && holeIndices.length;
  68484. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  68485. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  68486. if (hasHoles) {
  68487. for (var i = 0, len = holeIndices.length; i < len; i++) {
  68488. var start = holeIndices[i] * dim;
  68489. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68490. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  68491. }
  68492. }
  68493. var trianglesArea = 0;
  68494. for (i = 0; i < triangles.length; i += 3) {
  68495. var a = triangles[i] * dim;
  68496. var b = triangles[i + 1] * dim;
  68497. var c = triangles[i + 2] * dim;
  68498. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  68499. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  68500. }
  68501. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  68502. }
  68503. Earcut.deviation = deviation;
  68504. ;
  68505. function signedArea(data, start, end, dim) {
  68506. var sum = 0;
  68507. for (var i = start, j = end - dim; i < end; i += dim) {
  68508. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  68509. j = i;
  68510. }
  68511. return sum;
  68512. }
  68513. /**
  68514. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  68515. */
  68516. function flatten(data) {
  68517. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  68518. for (var i = 0; i < data.length; i++) {
  68519. for (var j = 0; j < data[i].length; j++) {
  68520. for (var d = 0; d < dim; d++)
  68521. result.vertices.push(data[i][j][d]);
  68522. }
  68523. if (i > 0) {
  68524. holeIndex += data[i - 1].length;
  68525. result.holes.push(holeIndex);
  68526. }
  68527. }
  68528. return result;
  68529. }
  68530. Earcut.flatten = flatten;
  68531. ;
  68532. })(Earcut || (Earcut = {}));
  68533. //# sourceMappingURL=babylon.earcut.js.map
  68534. var BABYLON;
  68535. (function (BABYLON) {
  68536. var IndexedVector2 = /** @class */ (function (_super) {
  68537. __extends(IndexedVector2, _super);
  68538. function IndexedVector2(original, index) {
  68539. var _this = _super.call(this, original.x, original.y) || this;
  68540. _this.index = index;
  68541. return _this;
  68542. }
  68543. return IndexedVector2;
  68544. }(BABYLON.Vector2));
  68545. var PolygonPoints = /** @class */ (function () {
  68546. function PolygonPoints() {
  68547. this.elements = new Array();
  68548. }
  68549. PolygonPoints.prototype.add = function (originalPoints) {
  68550. var _this = this;
  68551. var result = new Array();
  68552. originalPoints.forEach(function (point) {
  68553. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  68554. var newPoint = new IndexedVector2(point, _this.elements.length);
  68555. result.push(newPoint);
  68556. _this.elements.push(newPoint);
  68557. }
  68558. });
  68559. return result;
  68560. };
  68561. PolygonPoints.prototype.computeBounds = function () {
  68562. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68563. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68564. this.elements.forEach(function (point) {
  68565. // x
  68566. if (point.x < lmin.x) {
  68567. lmin.x = point.x;
  68568. }
  68569. else if (point.x > lmax.x) {
  68570. lmax.x = point.x;
  68571. }
  68572. // y
  68573. if (point.y < lmin.y) {
  68574. lmin.y = point.y;
  68575. }
  68576. else if (point.y > lmax.y) {
  68577. lmax.y = point.y;
  68578. }
  68579. });
  68580. return {
  68581. min: lmin,
  68582. max: lmax,
  68583. width: lmax.x - lmin.x,
  68584. height: lmax.y - lmin.y
  68585. };
  68586. };
  68587. return PolygonPoints;
  68588. }());
  68589. var Polygon = /** @class */ (function () {
  68590. function Polygon() {
  68591. }
  68592. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  68593. return [
  68594. new BABYLON.Vector2(xmin, ymin),
  68595. new BABYLON.Vector2(xmax, ymin),
  68596. new BABYLON.Vector2(xmax, ymax),
  68597. new BABYLON.Vector2(xmin, ymax)
  68598. ];
  68599. };
  68600. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  68601. if (cx === void 0) { cx = 0; }
  68602. if (cy === void 0) { cy = 0; }
  68603. if (numberOfSides === void 0) { numberOfSides = 32; }
  68604. var result = new Array();
  68605. var angle = 0;
  68606. var increment = (Math.PI * 2) / numberOfSides;
  68607. for (var i = 0; i < numberOfSides; i++) {
  68608. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  68609. angle -= increment;
  68610. }
  68611. return result;
  68612. };
  68613. Polygon.Parse = function (input) {
  68614. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  68615. var i, result = [];
  68616. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  68617. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  68618. }
  68619. return result;
  68620. };
  68621. Polygon.StartingAt = function (x, y) {
  68622. return BABYLON.Path2.StartingAt(x, y);
  68623. };
  68624. return Polygon;
  68625. }());
  68626. BABYLON.Polygon = Polygon;
  68627. var PolygonMeshBuilder = /** @class */ (function () {
  68628. function PolygonMeshBuilder(name, contours, scene) {
  68629. this._points = new PolygonPoints();
  68630. this._outlinepoints = new PolygonPoints();
  68631. this._holes = new Array();
  68632. this._epoints = new Array();
  68633. this._eholes = new Array();
  68634. this._name = name;
  68635. this._scene = scene;
  68636. var points;
  68637. if (contours instanceof BABYLON.Path2) {
  68638. points = contours.getPoints();
  68639. }
  68640. else {
  68641. points = contours;
  68642. }
  68643. this._addToepoint(points);
  68644. this._points.add(points);
  68645. this._outlinepoints.add(points);
  68646. }
  68647. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  68648. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  68649. var p = points_1[_i];
  68650. this._epoints.push(p.x, p.y);
  68651. }
  68652. };
  68653. PolygonMeshBuilder.prototype.addHole = function (hole) {
  68654. this._points.add(hole);
  68655. var holepoints = new PolygonPoints();
  68656. holepoints.add(hole);
  68657. this._holes.push(holepoints);
  68658. this._eholes.push(this._epoints.length / 2);
  68659. this._addToepoint(hole);
  68660. return this;
  68661. };
  68662. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  68663. var _this = this;
  68664. if (updatable === void 0) { updatable = false; }
  68665. if (depth === void 0) { depth = 0; }
  68666. var result = new BABYLON.Mesh(this._name, this._scene);
  68667. var normals = new Array();
  68668. var positions = new Array();
  68669. var uvs = new Array();
  68670. var bounds = this._points.computeBounds();
  68671. this._points.elements.forEach(function (p) {
  68672. normals.push(0, 1.0, 0);
  68673. positions.push(p.x, 0, p.y);
  68674. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  68675. });
  68676. var indices = new Array();
  68677. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  68678. for (var i = 0; i < res.length; i++) {
  68679. indices.push(res[i]);
  68680. }
  68681. if (depth > 0) {
  68682. var positionscount = (positions.length / 3); //get the current pointcount
  68683. this._points.elements.forEach(function (p) {
  68684. normals.push(0, -1.0, 0);
  68685. positions.push(p.x, -depth, p.y);
  68686. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  68687. });
  68688. var totalCount = indices.length;
  68689. for (var i = 0; i < totalCount; i += 3) {
  68690. var i0 = indices[i + 0];
  68691. var i1 = indices[i + 1];
  68692. var i2 = indices[i + 2];
  68693. indices.push(i2 + positionscount);
  68694. indices.push(i1 + positionscount);
  68695. indices.push(i0 + positionscount);
  68696. }
  68697. //Add the sides
  68698. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  68699. this._holes.forEach(function (hole) {
  68700. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  68701. });
  68702. }
  68703. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  68704. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  68705. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  68706. result.setIndices(indices);
  68707. return result;
  68708. };
  68709. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  68710. var StartIndex = positions.length / 3;
  68711. var ulength = 0;
  68712. for (var i = 0; i < points.elements.length; i++) {
  68713. var p = points.elements[i];
  68714. var p1;
  68715. if ((i + 1) > points.elements.length - 1) {
  68716. p1 = points.elements[0];
  68717. }
  68718. else {
  68719. p1 = points.elements[i + 1];
  68720. }
  68721. positions.push(p.x, 0, p.y);
  68722. positions.push(p.x, -depth, p.y);
  68723. positions.push(p1.x, 0, p1.y);
  68724. positions.push(p1.x, -depth, p1.y);
  68725. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  68726. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  68727. var v3 = v2.subtract(v1);
  68728. var v4 = new BABYLON.Vector3(0, 1, 0);
  68729. var vn = BABYLON.Vector3.Cross(v3, v4);
  68730. vn = vn.normalize();
  68731. uvs.push(ulength / bounds.width, 0);
  68732. uvs.push(ulength / bounds.width, 1);
  68733. ulength += v3.length();
  68734. uvs.push((ulength / bounds.width), 0);
  68735. uvs.push((ulength / bounds.width), 1);
  68736. if (!flip) {
  68737. normals.push(-vn.x, -vn.y, -vn.z);
  68738. normals.push(-vn.x, -vn.y, -vn.z);
  68739. normals.push(-vn.x, -vn.y, -vn.z);
  68740. normals.push(-vn.x, -vn.y, -vn.z);
  68741. indices.push(StartIndex);
  68742. indices.push(StartIndex + 1);
  68743. indices.push(StartIndex + 2);
  68744. indices.push(StartIndex + 1);
  68745. indices.push(StartIndex + 3);
  68746. indices.push(StartIndex + 2);
  68747. }
  68748. else {
  68749. normals.push(vn.x, vn.y, vn.z);
  68750. normals.push(vn.x, vn.y, vn.z);
  68751. normals.push(vn.x, vn.y, vn.z);
  68752. normals.push(vn.x, vn.y, vn.z);
  68753. indices.push(StartIndex);
  68754. indices.push(StartIndex + 2);
  68755. indices.push(StartIndex + 1);
  68756. indices.push(StartIndex + 1);
  68757. indices.push(StartIndex + 2);
  68758. indices.push(StartIndex + 3);
  68759. }
  68760. StartIndex += 4;
  68761. }
  68762. ;
  68763. };
  68764. return PolygonMeshBuilder;
  68765. }());
  68766. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  68767. })(BABYLON || (BABYLON = {}));
  68768. //# sourceMappingURL=babylon.polygonMesh.js.map
  68769. var BABYLON;
  68770. (function (BABYLON) {
  68771. // Unique ID when we import meshes from Babylon to CSG
  68772. var currentCSGMeshId = 0;
  68773. // # class Vertex
  68774. // Represents a vertex of a polygon. Use your own vertex class instead of this
  68775. // one to provide additional features like texture coordinates and vertex
  68776. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  68777. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  68778. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  68779. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  68780. // is not used anywhere else.
  68781. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  68782. var Vertex = /** @class */ (function () {
  68783. function Vertex(pos, normal, uv) {
  68784. this.pos = pos;
  68785. this.normal = normal;
  68786. this.uv = uv;
  68787. }
  68788. Vertex.prototype.clone = function () {
  68789. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  68790. };
  68791. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  68792. // orientation of a polygon is flipped.
  68793. Vertex.prototype.flip = function () {
  68794. this.normal = this.normal.scale(-1);
  68795. };
  68796. // Create a new vertex between this vertex and `other` by linearly
  68797. // interpolating all properties using a parameter of `t`. Subclasses should
  68798. // override this to interpolate additional properties.
  68799. Vertex.prototype.interpolate = function (other, t) {
  68800. 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));
  68801. };
  68802. return Vertex;
  68803. }());
  68804. // # class Plane
  68805. // Represents a plane in 3D space.
  68806. var Plane = /** @class */ (function () {
  68807. function Plane(normal, w) {
  68808. this.normal = normal;
  68809. this.w = w;
  68810. }
  68811. Plane.FromPoints = function (a, b, c) {
  68812. var v0 = c.subtract(a);
  68813. var v1 = b.subtract(a);
  68814. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  68815. return null;
  68816. }
  68817. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  68818. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  68819. };
  68820. Plane.prototype.clone = function () {
  68821. return new Plane(this.normal.clone(), this.w);
  68822. };
  68823. Plane.prototype.flip = function () {
  68824. this.normal.scaleInPlace(-1);
  68825. this.w = -this.w;
  68826. };
  68827. // Split `polygon` by this plane if needed, then put the polygon or polygon
  68828. // fragments in the appropriate lists. Coplanar polygons go into either
  68829. // `coplanarFront` or `coplanarBack` depending on their orientation with
  68830. // respect to this plane. Polygons in front or in back of this plane go into
  68831. // either `front` or `back`.
  68832. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  68833. var COPLANAR = 0;
  68834. var FRONT = 1;
  68835. var BACK = 2;
  68836. var SPANNING = 3;
  68837. // Classify each point as well as the entire polygon into one of the above
  68838. // four classes.
  68839. var polygonType = 0;
  68840. var types = [];
  68841. var i;
  68842. var t;
  68843. for (i = 0; i < polygon.vertices.length; i++) {
  68844. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  68845. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  68846. polygonType |= type;
  68847. types.push(type);
  68848. }
  68849. // Put the polygon in the correct list, splitting it when necessary.
  68850. switch (polygonType) {
  68851. case COPLANAR:
  68852. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  68853. break;
  68854. case FRONT:
  68855. front.push(polygon);
  68856. break;
  68857. case BACK:
  68858. back.push(polygon);
  68859. break;
  68860. case SPANNING:
  68861. var f = [], b = [];
  68862. for (i = 0; i < polygon.vertices.length; i++) {
  68863. var j = (i + 1) % polygon.vertices.length;
  68864. var ti = types[i], tj = types[j];
  68865. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  68866. if (ti !== BACK)
  68867. f.push(vi);
  68868. if (ti !== FRONT)
  68869. b.push(ti !== BACK ? vi.clone() : vi);
  68870. if ((ti | tj) === SPANNING) {
  68871. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  68872. var v = vi.interpolate(vj, t);
  68873. f.push(v);
  68874. b.push(v.clone());
  68875. }
  68876. }
  68877. var poly;
  68878. if (f.length >= 3) {
  68879. poly = new Polygon(f, polygon.shared);
  68880. if (poly.plane)
  68881. front.push(poly);
  68882. }
  68883. if (b.length >= 3) {
  68884. poly = new Polygon(b, polygon.shared);
  68885. if (poly.plane)
  68886. back.push(poly);
  68887. }
  68888. break;
  68889. }
  68890. };
  68891. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  68892. // point is on the plane.
  68893. Plane.EPSILON = 1e-5;
  68894. return Plane;
  68895. }());
  68896. // # class Polygon
  68897. // Represents a convex polygon. The vertices used to initialize a polygon must
  68898. // be coplanar and form a convex loop.
  68899. //
  68900. // Each convex polygon has a `shared` property, which is shared between all
  68901. // polygons that are clones of each other or were split from the same polygon.
  68902. // This can be used to define per-polygon properties (such as surface color).
  68903. var Polygon = /** @class */ (function () {
  68904. function Polygon(vertices, shared) {
  68905. this.vertices = vertices;
  68906. this.shared = shared;
  68907. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  68908. }
  68909. Polygon.prototype.clone = function () {
  68910. var vertices = this.vertices.map(function (v) { return v.clone(); });
  68911. return new Polygon(vertices, this.shared);
  68912. };
  68913. Polygon.prototype.flip = function () {
  68914. this.vertices.reverse().map(function (v) { v.flip(); });
  68915. this.plane.flip();
  68916. };
  68917. return Polygon;
  68918. }());
  68919. // # class Node
  68920. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  68921. // by picking a polygon to split along. That polygon (and all other coplanar
  68922. // polygons) are added directly to that node and the other polygons are added to
  68923. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  68924. // no distinction between internal and leaf nodes.
  68925. var Node = /** @class */ (function () {
  68926. function Node(polygons) {
  68927. this.plane = null;
  68928. this.front = null;
  68929. this.back = null;
  68930. this.polygons = new Array();
  68931. if (polygons) {
  68932. this.build(polygons);
  68933. }
  68934. }
  68935. Node.prototype.clone = function () {
  68936. var node = new Node();
  68937. node.plane = this.plane && this.plane.clone();
  68938. node.front = this.front && this.front.clone();
  68939. node.back = this.back && this.back.clone();
  68940. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  68941. return node;
  68942. };
  68943. // Convert solid space to empty space and empty space to solid space.
  68944. Node.prototype.invert = function () {
  68945. for (var i = 0; i < this.polygons.length; i++) {
  68946. this.polygons[i].flip();
  68947. }
  68948. if (this.plane) {
  68949. this.plane.flip();
  68950. }
  68951. if (this.front) {
  68952. this.front.invert();
  68953. }
  68954. if (this.back) {
  68955. this.back.invert();
  68956. }
  68957. var temp = this.front;
  68958. this.front = this.back;
  68959. this.back = temp;
  68960. };
  68961. // Recursively remove all polygons in `polygons` that are inside this BSP
  68962. // tree.
  68963. Node.prototype.clipPolygons = function (polygons) {
  68964. if (!this.plane)
  68965. return polygons.slice();
  68966. var front = new Array(), back = new Array();
  68967. for (var i = 0; i < polygons.length; i++) {
  68968. this.plane.splitPolygon(polygons[i], front, back, front, back);
  68969. }
  68970. if (this.front) {
  68971. front = this.front.clipPolygons(front);
  68972. }
  68973. if (this.back) {
  68974. back = this.back.clipPolygons(back);
  68975. }
  68976. else {
  68977. back = [];
  68978. }
  68979. return front.concat(back);
  68980. };
  68981. // Remove all polygons in this BSP tree that are inside the other BSP tree
  68982. // `bsp`.
  68983. Node.prototype.clipTo = function (bsp) {
  68984. this.polygons = bsp.clipPolygons(this.polygons);
  68985. if (this.front)
  68986. this.front.clipTo(bsp);
  68987. if (this.back)
  68988. this.back.clipTo(bsp);
  68989. };
  68990. // Return a list of all polygons in this BSP tree.
  68991. Node.prototype.allPolygons = function () {
  68992. var polygons = this.polygons.slice();
  68993. if (this.front)
  68994. polygons = polygons.concat(this.front.allPolygons());
  68995. if (this.back)
  68996. polygons = polygons.concat(this.back.allPolygons());
  68997. return polygons;
  68998. };
  68999. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  69000. // new polygons are filtered down to the bottom of the tree and become new
  69001. // nodes there. Each set of polygons is partitioned using the first polygon
  69002. // (no heuristic is used to pick a good split).
  69003. Node.prototype.build = function (polygons) {
  69004. if (!polygons.length)
  69005. return;
  69006. if (!this.plane)
  69007. this.plane = polygons[0].plane.clone();
  69008. var front = new Array(), back = new Array();
  69009. for (var i = 0; i < polygons.length; i++) {
  69010. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  69011. }
  69012. if (front.length) {
  69013. if (!this.front)
  69014. this.front = new Node();
  69015. this.front.build(front);
  69016. }
  69017. if (back.length) {
  69018. if (!this.back)
  69019. this.back = new Node();
  69020. this.back.build(back);
  69021. }
  69022. };
  69023. return Node;
  69024. }());
  69025. var CSG = /** @class */ (function () {
  69026. function CSG() {
  69027. this.polygons = new Array();
  69028. }
  69029. // Convert BABYLON.Mesh to BABYLON.CSG
  69030. CSG.FromMesh = function (mesh) {
  69031. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  69032. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  69033. if (mesh instanceof BABYLON.Mesh) {
  69034. mesh.computeWorldMatrix(true);
  69035. matrix = mesh.getWorldMatrix();
  69036. meshPosition = mesh.position.clone();
  69037. meshRotation = mesh.rotation.clone();
  69038. if (mesh.rotationQuaternion) {
  69039. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  69040. }
  69041. meshScaling = mesh.scaling.clone();
  69042. }
  69043. else {
  69044. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  69045. }
  69046. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69047. var subMeshes = mesh.subMeshes;
  69048. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  69049. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  69050. vertices = [];
  69051. for (var j = 0; j < 3; j++) {
  69052. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  69053. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  69054. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  69055. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  69056. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  69057. vertex = new Vertex(position, normal, uv);
  69058. vertices.push(vertex);
  69059. }
  69060. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  69061. // To handle the case of degenerated triangle
  69062. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  69063. if (polygon.plane)
  69064. polygons.push(polygon);
  69065. }
  69066. }
  69067. var csg = CSG.FromPolygons(polygons);
  69068. csg.matrix = matrix;
  69069. csg.position = meshPosition;
  69070. csg.rotation = meshRotation;
  69071. csg.scaling = meshScaling;
  69072. csg.rotationQuaternion = meshRotationQuaternion;
  69073. currentCSGMeshId++;
  69074. return csg;
  69075. };
  69076. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  69077. CSG.FromPolygons = function (polygons) {
  69078. var csg = new CSG();
  69079. csg.polygons = polygons;
  69080. return csg;
  69081. };
  69082. CSG.prototype.clone = function () {
  69083. var csg = new CSG();
  69084. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  69085. csg.copyTransformAttributes(this);
  69086. return csg;
  69087. };
  69088. CSG.prototype.union = function (csg) {
  69089. var a = new Node(this.clone().polygons);
  69090. var b = new Node(csg.clone().polygons);
  69091. a.clipTo(b);
  69092. b.clipTo(a);
  69093. b.invert();
  69094. b.clipTo(a);
  69095. b.invert();
  69096. a.build(b.allPolygons());
  69097. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69098. };
  69099. CSG.prototype.unionInPlace = function (csg) {
  69100. var a = new Node(this.polygons);
  69101. var b = new Node(csg.polygons);
  69102. a.clipTo(b);
  69103. b.clipTo(a);
  69104. b.invert();
  69105. b.clipTo(a);
  69106. b.invert();
  69107. a.build(b.allPolygons());
  69108. this.polygons = a.allPolygons();
  69109. };
  69110. CSG.prototype.subtract = function (csg) {
  69111. var a = new Node(this.clone().polygons);
  69112. var b = new Node(csg.clone().polygons);
  69113. a.invert();
  69114. a.clipTo(b);
  69115. b.clipTo(a);
  69116. b.invert();
  69117. b.clipTo(a);
  69118. b.invert();
  69119. a.build(b.allPolygons());
  69120. a.invert();
  69121. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69122. };
  69123. CSG.prototype.subtractInPlace = function (csg) {
  69124. var a = new Node(this.polygons);
  69125. var b = new Node(csg.polygons);
  69126. a.invert();
  69127. a.clipTo(b);
  69128. b.clipTo(a);
  69129. b.invert();
  69130. b.clipTo(a);
  69131. b.invert();
  69132. a.build(b.allPolygons());
  69133. a.invert();
  69134. this.polygons = a.allPolygons();
  69135. };
  69136. CSG.prototype.intersect = function (csg) {
  69137. var a = new Node(this.clone().polygons);
  69138. var b = new Node(csg.clone().polygons);
  69139. a.invert();
  69140. b.clipTo(a);
  69141. b.invert();
  69142. a.clipTo(b);
  69143. b.clipTo(a);
  69144. a.build(b.allPolygons());
  69145. a.invert();
  69146. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69147. };
  69148. CSG.prototype.intersectInPlace = function (csg) {
  69149. var a = new Node(this.polygons);
  69150. var b = new Node(csg.polygons);
  69151. a.invert();
  69152. b.clipTo(a);
  69153. b.invert();
  69154. a.clipTo(b);
  69155. b.clipTo(a);
  69156. a.build(b.allPolygons());
  69157. a.invert();
  69158. this.polygons = a.allPolygons();
  69159. };
  69160. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  69161. // not modified.
  69162. CSG.prototype.inverse = function () {
  69163. var csg = this.clone();
  69164. csg.inverseInPlace();
  69165. return csg;
  69166. };
  69167. CSG.prototype.inverseInPlace = function () {
  69168. this.polygons.map(function (p) { p.flip(); });
  69169. };
  69170. // This is used to keep meshes transformations so they can be restored
  69171. // when we build back a Babylon Mesh
  69172. // NB : All CSG operations are performed in world coordinates
  69173. CSG.prototype.copyTransformAttributes = function (csg) {
  69174. this.matrix = csg.matrix;
  69175. this.position = csg.position;
  69176. this.rotation = csg.rotation;
  69177. this.scaling = csg.scaling;
  69178. this.rotationQuaternion = csg.rotationQuaternion;
  69179. return this;
  69180. };
  69181. // Build Raw mesh from CSG
  69182. // Coordinates here are in world space
  69183. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69184. var matrix = this.matrix.clone();
  69185. matrix.invert();
  69186. 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;
  69187. if (keepSubMeshes) {
  69188. // Sort Polygons, since subMeshes are indices range
  69189. polygons.sort(function (a, b) {
  69190. if (a.shared.meshId === b.shared.meshId) {
  69191. return a.shared.subMeshId - b.shared.subMeshId;
  69192. }
  69193. else {
  69194. return a.shared.meshId - b.shared.meshId;
  69195. }
  69196. });
  69197. }
  69198. for (var i = 0, il = polygons.length; i < il; i++) {
  69199. polygon = polygons[i];
  69200. // Building SubMeshes
  69201. if (!subMesh_dict[polygon.shared.meshId]) {
  69202. subMesh_dict[polygon.shared.meshId] = {};
  69203. }
  69204. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69205. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69206. indexStart: +Infinity,
  69207. indexEnd: -Infinity,
  69208. materialIndex: polygon.shared.materialIndex
  69209. };
  69210. }
  69211. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69212. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69213. polygonIndices[0] = 0;
  69214. polygonIndices[1] = j - 1;
  69215. polygonIndices[2] = j;
  69216. for (var k = 0; k < 3; k++) {
  69217. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69218. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69219. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69220. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69221. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69222. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69223. // Check if 2 points can be merged
  69224. if (!(typeof vertex_idx !== 'undefined' &&
  69225. normals[vertex_idx * 3] === localNormal.x &&
  69226. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69227. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69228. uvs[vertex_idx * 2] === uv.x &&
  69229. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69230. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69231. uvs.push(uv.x, uv.y);
  69232. normals.push(normal.x, normal.y, normal.z);
  69233. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69234. }
  69235. indices.push(vertex_idx);
  69236. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69237. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69238. currentIndex++;
  69239. }
  69240. }
  69241. }
  69242. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69243. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69244. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69245. mesh.setIndices(indices, null);
  69246. if (keepSubMeshes) {
  69247. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69248. var materialIndexOffset = 0, materialMaxIndex;
  69249. mesh.subMeshes = new Array();
  69250. for (var m in subMesh_dict) {
  69251. materialMaxIndex = -1;
  69252. for (var sm in subMesh_dict[m]) {
  69253. subMesh_obj = subMesh_dict[m][sm];
  69254. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69255. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69256. }
  69257. materialIndexOffset += ++materialMaxIndex;
  69258. }
  69259. }
  69260. return mesh;
  69261. };
  69262. // Build Mesh from CSG taking material and transforms into account
  69263. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69264. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69265. mesh.material = material;
  69266. mesh.position.copyFrom(this.position);
  69267. mesh.rotation.copyFrom(this.rotation);
  69268. if (this.rotationQuaternion) {
  69269. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69270. }
  69271. mesh.scaling.copyFrom(this.scaling);
  69272. mesh.computeWorldMatrix(true);
  69273. return mesh;
  69274. };
  69275. return CSG;
  69276. }());
  69277. BABYLON.CSG = CSG;
  69278. })(BABYLON || (BABYLON = {}));
  69279. //# sourceMappingURL=babylon.csg.js.map
  69280. var BABYLON;
  69281. (function (BABYLON) {
  69282. var LensFlare = /** @class */ (function () {
  69283. function LensFlare(size, position, color, imgUrl, system) {
  69284. this.size = size;
  69285. this.position = position;
  69286. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69287. this.color = color || new BABYLON.Color3(1, 1, 1);
  69288. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69289. this._system = system;
  69290. system.lensFlares.push(this);
  69291. }
  69292. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69293. return new LensFlare(size, position, color, imgUrl, system);
  69294. };
  69295. LensFlare.prototype.dispose = function () {
  69296. if (this.texture) {
  69297. this.texture.dispose();
  69298. }
  69299. // Remove from scene
  69300. var index = this._system.lensFlares.indexOf(this);
  69301. this._system.lensFlares.splice(index, 1);
  69302. };
  69303. ;
  69304. return LensFlare;
  69305. }());
  69306. BABYLON.LensFlare = LensFlare;
  69307. })(BABYLON || (BABYLON = {}));
  69308. //# sourceMappingURL=babylon.lensFlare.js.map
  69309. var BABYLON;
  69310. (function (BABYLON) {
  69311. var LensFlareSystem = /** @class */ (function () {
  69312. function LensFlareSystem(name, emitter, scene) {
  69313. this.name = name;
  69314. this.lensFlares = new Array();
  69315. this.borderLimit = 300;
  69316. this.viewportBorder = 0;
  69317. this.layerMask = 0x0FFFFFFF;
  69318. this._vertexBuffers = {};
  69319. this._isEnabled = true;
  69320. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69321. this._emitter = emitter;
  69322. this.id = name;
  69323. scene.lensFlareSystems.push(this);
  69324. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69325. var engine = scene.getEngine();
  69326. // VBO
  69327. var vertices = [];
  69328. vertices.push(1, 1);
  69329. vertices.push(-1, 1);
  69330. vertices.push(-1, -1);
  69331. vertices.push(1, -1);
  69332. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69333. // Indices
  69334. var indices = [];
  69335. indices.push(0);
  69336. indices.push(1);
  69337. indices.push(2);
  69338. indices.push(0);
  69339. indices.push(2);
  69340. indices.push(3);
  69341. this._indexBuffer = engine.createIndexBuffer(indices);
  69342. // Effects
  69343. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69344. }
  69345. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69346. get: function () {
  69347. return this._isEnabled;
  69348. },
  69349. set: function (value) {
  69350. this._isEnabled = value;
  69351. },
  69352. enumerable: true,
  69353. configurable: true
  69354. });
  69355. LensFlareSystem.prototype.getScene = function () {
  69356. return this._scene;
  69357. };
  69358. LensFlareSystem.prototype.getEmitter = function () {
  69359. return this._emitter;
  69360. };
  69361. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69362. this._emitter = newEmitter;
  69363. };
  69364. LensFlareSystem.prototype.getEmitterPosition = function () {
  69365. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69366. };
  69367. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69368. var position = this.getEmitterPosition();
  69369. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69370. this._positionX = position.x;
  69371. this._positionY = position.y;
  69372. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69373. if (this.viewportBorder > 0) {
  69374. globalViewport.x -= this.viewportBorder;
  69375. globalViewport.y -= this.viewportBorder;
  69376. globalViewport.width += this.viewportBorder * 2;
  69377. globalViewport.height += this.viewportBorder * 2;
  69378. position.x += this.viewportBorder;
  69379. position.y += this.viewportBorder;
  69380. this._positionX += this.viewportBorder;
  69381. this._positionY += this.viewportBorder;
  69382. }
  69383. if (position.z > 0) {
  69384. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69385. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69386. return true;
  69387. }
  69388. return true;
  69389. }
  69390. return false;
  69391. };
  69392. LensFlareSystem.prototype._isVisible = function () {
  69393. if (!this._isEnabled || !this._scene.activeCamera) {
  69394. return false;
  69395. }
  69396. var emitterPosition = this.getEmitterPosition();
  69397. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69398. var distance = direction.length();
  69399. direction.normalize();
  69400. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69401. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69402. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69403. };
  69404. LensFlareSystem.prototype.render = function () {
  69405. if (!this._effect.isReady() || !this._scene.activeCamera)
  69406. return false;
  69407. var engine = this._scene.getEngine();
  69408. var viewport = this._scene.activeCamera.viewport;
  69409. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  69410. // Position
  69411. if (!this.computeEffectivePosition(globalViewport)) {
  69412. return false;
  69413. }
  69414. // Visibility
  69415. if (!this._isVisible()) {
  69416. return false;
  69417. }
  69418. // Intensity
  69419. var awayX;
  69420. var awayY;
  69421. if (this._positionX < this.borderLimit + globalViewport.x) {
  69422. awayX = this.borderLimit + globalViewport.x - this._positionX;
  69423. }
  69424. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  69425. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  69426. }
  69427. else {
  69428. awayX = 0;
  69429. }
  69430. if (this._positionY < this.borderLimit + globalViewport.y) {
  69431. awayY = this.borderLimit + globalViewport.y - this._positionY;
  69432. }
  69433. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  69434. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  69435. }
  69436. else {
  69437. awayY = 0;
  69438. }
  69439. var away = (awayX > awayY) ? awayX : awayY;
  69440. away -= this.viewportBorder;
  69441. if (away > this.borderLimit) {
  69442. away = this.borderLimit;
  69443. }
  69444. var intensity = 1.0 - (away / this.borderLimit);
  69445. if (intensity < 0) {
  69446. return false;
  69447. }
  69448. if (intensity > 1.0) {
  69449. intensity = 1.0;
  69450. }
  69451. if (this.viewportBorder > 0) {
  69452. globalViewport.x += this.viewportBorder;
  69453. globalViewport.y += this.viewportBorder;
  69454. globalViewport.width -= this.viewportBorder * 2;
  69455. globalViewport.height -= this.viewportBorder * 2;
  69456. this._positionX -= this.viewportBorder;
  69457. this._positionY -= this.viewportBorder;
  69458. }
  69459. // Position
  69460. var centerX = globalViewport.x + globalViewport.width / 2;
  69461. var centerY = globalViewport.y + globalViewport.height / 2;
  69462. var distX = centerX - this._positionX;
  69463. var distY = centerY - this._positionY;
  69464. // Effects
  69465. engine.enableEffect(this._effect);
  69466. engine.setState(false);
  69467. engine.setDepthBuffer(false);
  69468. // VBOs
  69469. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69470. // Flares
  69471. for (var index = 0; index < this.lensFlares.length; index++) {
  69472. var flare = this.lensFlares[index];
  69473. engine.setAlphaMode(flare.alphaMode);
  69474. var x = centerX - (distX * flare.position);
  69475. var y = centerY - (distY * flare.position);
  69476. var cw = flare.size;
  69477. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  69478. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  69479. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  69480. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  69481. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  69482. // Texture
  69483. this._effect.setTexture("textureSampler", flare.texture);
  69484. // Color
  69485. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  69486. // Draw order
  69487. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69488. }
  69489. engine.setDepthBuffer(true);
  69490. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69491. return true;
  69492. };
  69493. LensFlareSystem.prototype.dispose = function () {
  69494. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69495. if (vertexBuffer) {
  69496. vertexBuffer.dispose();
  69497. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69498. }
  69499. if (this._indexBuffer) {
  69500. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69501. this._indexBuffer = null;
  69502. }
  69503. while (this.lensFlares.length) {
  69504. this.lensFlares[0].dispose();
  69505. }
  69506. // Remove from scene
  69507. var index = this._scene.lensFlareSystems.indexOf(this);
  69508. this._scene.lensFlareSystems.splice(index, 1);
  69509. };
  69510. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  69511. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  69512. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  69513. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  69514. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  69515. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  69516. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  69517. var parsedFlare = parsedLensFlareSystem.flares[index];
  69518. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  69519. }
  69520. return lensFlareSystem;
  69521. };
  69522. LensFlareSystem.prototype.serialize = function () {
  69523. var serializationObject = {};
  69524. serializationObject.id = this.id;
  69525. serializationObject.name = this.name;
  69526. serializationObject.emitterId = this.getEmitter().id;
  69527. serializationObject.borderLimit = this.borderLimit;
  69528. serializationObject.flares = [];
  69529. for (var index = 0; index < this.lensFlares.length; index++) {
  69530. var flare = this.lensFlares[index];
  69531. serializationObject.flares.push({
  69532. size: flare.size,
  69533. position: flare.position,
  69534. color: flare.color.asArray(),
  69535. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  69536. });
  69537. }
  69538. return serializationObject;
  69539. };
  69540. return LensFlareSystem;
  69541. }());
  69542. BABYLON.LensFlareSystem = LensFlareSystem;
  69543. })(BABYLON || (BABYLON = {}));
  69544. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  69545. var BABYLON;
  69546. (function (BABYLON) {
  69547. /**
  69548. * This is a holder class for the physics joint created by the physics plugin.
  69549. * It holds a set of functions to control the underlying joint.
  69550. */
  69551. var PhysicsJoint = /** @class */ (function () {
  69552. function PhysicsJoint(type, jointData) {
  69553. this.type = type;
  69554. this.jointData = jointData;
  69555. jointData.nativeParams = jointData.nativeParams || {};
  69556. }
  69557. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  69558. get: function () {
  69559. return this._physicsJoint;
  69560. },
  69561. set: function (newJoint) {
  69562. if (this._physicsJoint) {
  69563. //remove from the wolrd
  69564. }
  69565. this._physicsJoint = newJoint;
  69566. },
  69567. enumerable: true,
  69568. configurable: true
  69569. });
  69570. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  69571. set: function (physicsPlugin) {
  69572. this._physicsPlugin = physicsPlugin;
  69573. },
  69574. enumerable: true,
  69575. configurable: true
  69576. });
  69577. /**
  69578. * Execute a function that is physics-plugin specific.
  69579. * @param {Function} func the function that will be executed.
  69580. * It accepts two parameters: the physics world and the physics joint.
  69581. */
  69582. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  69583. func(this._physicsPlugin.world, this._physicsJoint);
  69584. };
  69585. //TODO check if the native joints are the same
  69586. //Joint Types
  69587. PhysicsJoint.DistanceJoint = 0;
  69588. PhysicsJoint.HingeJoint = 1;
  69589. PhysicsJoint.BallAndSocketJoint = 2;
  69590. PhysicsJoint.WheelJoint = 3;
  69591. PhysicsJoint.SliderJoint = 4;
  69592. //OIMO
  69593. PhysicsJoint.PrismaticJoint = 5;
  69594. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  69595. PhysicsJoint.UniversalJoint = 6;
  69596. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  69597. //Cannon
  69598. //Similar to a Ball-Joint. Different in params
  69599. PhysicsJoint.PointToPointJoint = 8;
  69600. //Cannon only at the moment
  69601. PhysicsJoint.SpringJoint = 9;
  69602. PhysicsJoint.LockJoint = 10;
  69603. return PhysicsJoint;
  69604. }());
  69605. BABYLON.PhysicsJoint = PhysicsJoint;
  69606. /**
  69607. * A class representing a physics distance joint.
  69608. */
  69609. var DistanceJoint = /** @class */ (function (_super) {
  69610. __extends(DistanceJoint, _super);
  69611. function DistanceJoint(jointData) {
  69612. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  69613. }
  69614. /**
  69615. * Update the predefined distance.
  69616. */
  69617. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  69618. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  69619. };
  69620. return DistanceJoint;
  69621. }(PhysicsJoint));
  69622. BABYLON.DistanceJoint = DistanceJoint;
  69623. var MotorEnabledJoint = /** @class */ (function (_super) {
  69624. __extends(MotorEnabledJoint, _super);
  69625. function MotorEnabledJoint(type, jointData) {
  69626. return _super.call(this, type, jointData) || this;
  69627. }
  69628. /**
  69629. * Set the motor values.
  69630. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69631. * @param {number} force the force to apply
  69632. * @param {number} maxForce max force for this motor.
  69633. */
  69634. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  69635. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69636. };
  69637. /**
  69638. * Set the motor's limits.
  69639. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69640. */
  69641. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69642. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69643. };
  69644. return MotorEnabledJoint;
  69645. }(PhysicsJoint));
  69646. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  69647. /**
  69648. * This class represents a single hinge physics joint
  69649. */
  69650. var HingeJoint = /** @class */ (function (_super) {
  69651. __extends(HingeJoint, _super);
  69652. function HingeJoint(jointData) {
  69653. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  69654. }
  69655. /**
  69656. * Set the motor values.
  69657. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69658. * @param {number} force the force to apply
  69659. * @param {number} maxForce max force for this motor.
  69660. */
  69661. HingeJoint.prototype.setMotor = function (force, maxForce) {
  69662. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69663. };
  69664. /**
  69665. * Set the motor's limits.
  69666. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69667. */
  69668. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69669. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69670. };
  69671. return HingeJoint;
  69672. }(MotorEnabledJoint));
  69673. BABYLON.HingeJoint = HingeJoint;
  69674. /**
  69675. * This class represents a dual hinge physics joint (same as wheel joint)
  69676. */
  69677. var Hinge2Joint = /** @class */ (function (_super) {
  69678. __extends(Hinge2Joint, _super);
  69679. function Hinge2Joint(jointData) {
  69680. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  69681. }
  69682. /**
  69683. * Set the motor values.
  69684. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69685. * @param {number} force the force to apply
  69686. * @param {number} maxForce max force for this motor.
  69687. * @param {motorIndex} the motor's index, 0 or 1.
  69688. */
  69689. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  69690. if (motorIndex === void 0) { motorIndex = 0; }
  69691. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  69692. };
  69693. /**
  69694. * Set the motor limits.
  69695. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69696. * @param {number} upperLimit the upper limit
  69697. * @param {number} lowerLimit lower limit
  69698. * @param {motorIndex} the motor's index, 0 or 1.
  69699. */
  69700. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  69701. if (motorIndex === void 0) { motorIndex = 0; }
  69702. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  69703. };
  69704. return Hinge2Joint;
  69705. }(MotorEnabledJoint));
  69706. BABYLON.Hinge2Joint = Hinge2Joint;
  69707. })(BABYLON || (BABYLON = {}));
  69708. //# sourceMappingURL=babylon.physicsJoint.js.map
  69709. var BABYLON;
  69710. (function (BABYLON) {
  69711. var PhysicsImpostor = /** @class */ (function () {
  69712. function PhysicsImpostor(object, type, _options, _scene) {
  69713. if (_options === void 0) { _options = { mass: 0 }; }
  69714. var _this = this;
  69715. this.object = object;
  69716. this.type = type;
  69717. this._options = _options;
  69718. this._scene = _scene;
  69719. this._bodyUpdateRequired = false;
  69720. this._onBeforePhysicsStepCallbacks = new Array();
  69721. this._onAfterPhysicsStepCallbacks = new Array();
  69722. this._onPhysicsCollideCallbacks = [];
  69723. this._deltaPosition = BABYLON.Vector3.Zero();
  69724. this._isDisposed = false;
  69725. //temp variables for parent rotation calculations
  69726. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  69727. this._tmpQuat = new BABYLON.Quaternion();
  69728. this._tmpQuat2 = new BABYLON.Quaternion();
  69729. /**
  69730. * this function is executed by the physics engine.
  69731. */
  69732. this.beforeStep = function () {
  69733. if (!_this._physicsEngine) {
  69734. return;
  69735. }
  69736. _this.object.translate(_this._deltaPosition, -1);
  69737. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  69738. _this.object.computeWorldMatrix(false);
  69739. if (_this.object.parent && _this.object.rotationQuaternion) {
  69740. _this.getParentsRotation();
  69741. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  69742. }
  69743. else {
  69744. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  69745. }
  69746. if (!_this._options.disableBidirectionalTransformation) {
  69747. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  69748. }
  69749. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  69750. func(_this);
  69751. });
  69752. };
  69753. /**
  69754. * this function is executed by the physics engine.
  69755. */
  69756. this.afterStep = function () {
  69757. if (!_this._physicsEngine) {
  69758. return;
  69759. }
  69760. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  69761. func(_this);
  69762. });
  69763. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  69764. // object has now its world rotation. needs to be converted to local.
  69765. if (_this.object.parent && _this.object.rotationQuaternion) {
  69766. _this.getParentsRotation();
  69767. _this._tmpQuat.conjugateInPlace();
  69768. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  69769. }
  69770. // take the position set and make it the absolute position of this object.
  69771. _this.object.setAbsolutePosition(_this.object.position);
  69772. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  69773. _this.object.translate(_this._deltaPosition, 1);
  69774. };
  69775. /**
  69776. * Legacy collision detection event support
  69777. */
  69778. this.onCollideEvent = null;
  69779. //event and body object due to cannon's event-based architecture.
  69780. this.onCollide = function (e) {
  69781. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  69782. return;
  69783. }
  69784. if (!_this._physicsEngine) {
  69785. return;
  69786. }
  69787. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  69788. if (otherImpostor) {
  69789. // Legacy collision detection event support
  69790. if (_this.onCollideEvent) {
  69791. _this.onCollideEvent(_this, otherImpostor);
  69792. }
  69793. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  69794. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  69795. }).forEach(function (obj) {
  69796. obj.callback(_this, otherImpostor);
  69797. });
  69798. }
  69799. };
  69800. //sanity check!
  69801. if (!this.object) {
  69802. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  69803. return;
  69804. }
  69805. //legacy support for old syntax.
  69806. if (!this._scene && object.getScene) {
  69807. this._scene = object.getScene();
  69808. }
  69809. if (!this._scene) {
  69810. return;
  69811. }
  69812. this._physicsEngine = this._scene.getPhysicsEngine();
  69813. if (!this._physicsEngine) {
  69814. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  69815. }
  69816. else {
  69817. //set the object's quaternion, if not set
  69818. if (!this.object.rotationQuaternion) {
  69819. if (this.object.rotation) {
  69820. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  69821. }
  69822. else {
  69823. this.object.rotationQuaternion = new BABYLON.Quaternion();
  69824. }
  69825. }
  69826. //default options params
  69827. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  69828. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  69829. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  69830. this._joints = [];
  69831. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  69832. if (!this.object.parent || this._options.ignoreParent) {
  69833. this._init();
  69834. }
  69835. else if (this.object.parent.physicsImpostor) {
  69836. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  69837. }
  69838. }
  69839. }
  69840. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  69841. get: function () {
  69842. return this._isDisposed;
  69843. },
  69844. enumerable: true,
  69845. configurable: true
  69846. });
  69847. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  69848. get: function () {
  69849. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  69850. },
  69851. set: function (value) {
  69852. this.setMass(value);
  69853. },
  69854. enumerable: true,
  69855. configurable: true
  69856. });
  69857. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  69858. get: function () {
  69859. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  69860. },
  69861. set: function (value) {
  69862. if (!this._physicsEngine) {
  69863. return;
  69864. }
  69865. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  69866. },
  69867. enumerable: true,
  69868. configurable: true
  69869. });
  69870. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  69871. get: function () {
  69872. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  69873. },
  69874. set: function (value) {
  69875. if (!this._physicsEngine) {
  69876. return;
  69877. }
  69878. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  69879. },
  69880. enumerable: true,
  69881. configurable: true
  69882. });
  69883. /**
  69884. * This function will completly initialize this impostor.
  69885. * It will create a new body - but only if this mesh has no parent.
  69886. * If it has, this impostor will not be used other than to define the impostor
  69887. * of the child mesh.
  69888. */
  69889. PhysicsImpostor.prototype._init = function () {
  69890. if (!this._physicsEngine) {
  69891. return;
  69892. }
  69893. this._physicsEngine.removeImpostor(this);
  69894. this.physicsBody = null;
  69895. this._parent = this._parent || this._getPhysicsParent();
  69896. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  69897. this._physicsEngine.addImpostor(this);
  69898. }
  69899. };
  69900. PhysicsImpostor.prototype._getPhysicsParent = function () {
  69901. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  69902. var parentMesh = this.object.parent;
  69903. return parentMesh.physicsImpostor;
  69904. }
  69905. return null;
  69906. };
  69907. /**
  69908. * Should a new body be generated.
  69909. */
  69910. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  69911. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  69912. };
  69913. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  69914. this.forceUpdate();
  69915. };
  69916. /**
  69917. * Force a regeneration of this or the parent's impostor's body.
  69918. * Use under cautious - This will remove all joints already implemented.
  69919. */
  69920. PhysicsImpostor.prototype.forceUpdate = function () {
  69921. this._init();
  69922. if (this.parent && !this._options.ignoreParent) {
  69923. this.parent.forceUpdate();
  69924. }
  69925. };
  69926. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  69927. /*public get mesh(): AbstractMesh {
  69928. return this._mesh;
  69929. }*/
  69930. /**
  69931. * Gets the body that holds this impostor. Either its own, or its parent.
  69932. */
  69933. get: function () {
  69934. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  69935. },
  69936. /**
  69937. * Set the physics body. Used mainly by the physics engine/plugin
  69938. */
  69939. set: function (physicsBody) {
  69940. if (this._physicsBody && this._physicsEngine) {
  69941. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  69942. }
  69943. this._physicsBody = physicsBody;
  69944. this.resetUpdateFlags();
  69945. },
  69946. enumerable: true,
  69947. configurable: true
  69948. });
  69949. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  69950. get: function () {
  69951. return !this._options.ignoreParent && this._parent ? this._parent : null;
  69952. },
  69953. set: function (value) {
  69954. this._parent = value;
  69955. },
  69956. enumerable: true,
  69957. configurable: true
  69958. });
  69959. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  69960. this._bodyUpdateRequired = false;
  69961. };
  69962. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  69963. if (this.object.getBoundingInfo) {
  69964. var q = this.object.rotationQuaternion;
  69965. //reset rotation
  69966. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  69967. //calculate the world matrix with no rotation
  69968. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69969. var boundingInfo = this.object.getBoundingInfo();
  69970. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  69971. //bring back the rotation
  69972. this.object.rotationQuaternion = q;
  69973. //calculate the world matrix with the new rotation
  69974. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69975. return size;
  69976. }
  69977. else {
  69978. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  69979. }
  69980. };
  69981. PhysicsImpostor.prototype.getObjectCenter = function () {
  69982. if (this.object.getBoundingInfo) {
  69983. var boundingInfo = this.object.getBoundingInfo();
  69984. return boundingInfo.boundingBox.centerWorld;
  69985. }
  69986. else {
  69987. return this.object.position;
  69988. }
  69989. };
  69990. /**
  69991. * Get a specific parametes from the options parameter.
  69992. */
  69993. PhysicsImpostor.prototype.getParam = function (paramName) {
  69994. return this._options[paramName];
  69995. };
  69996. /**
  69997. * Sets a specific parameter in the options given to the physics plugin
  69998. */
  69999. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  70000. this._options[paramName] = value;
  70001. this._bodyUpdateRequired = true;
  70002. };
  70003. /**
  70004. * Specifically change the body's mass option. Won't recreate the physics body object
  70005. */
  70006. PhysicsImpostor.prototype.setMass = function (mass) {
  70007. if (this.getParam("mass") !== mass) {
  70008. this.setParam("mass", mass);
  70009. }
  70010. if (this._physicsEngine) {
  70011. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  70012. }
  70013. };
  70014. PhysicsImpostor.prototype.getLinearVelocity = function () {
  70015. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  70016. };
  70017. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  70018. if (this._physicsEngine) {
  70019. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  70020. }
  70021. };
  70022. PhysicsImpostor.prototype.getAngularVelocity = function () {
  70023. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  70024. };
  70025. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  70026. if (this._physicsEngine) {
  70027. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  70028. }
  70029. };
  70030. /**
  70031. * Execute a function with the physics plugin native code.
  70032. * Provide a function the will have two variables - the world object and the physics body object.
  70033. */
  70034. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  70035. if (this._physicsEngine) {
  70036. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  70037. }
  70038. };
  70039. /**
  70040. * Register a function that will be executed before the physics world is stepping forward.
  70041. */
  70042. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  70043. this._onBeforePhysicsStepCallbacks.push(func);
  70044. };
  70045. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  70046. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  70047. if (index > -1) {
  70048. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  70049. }
  70050. else {
  70051. BABYLON.Tools.Warn("Function to remove was not found");
  70052. }
  70053. };
  70054. /**
  70055. * Register a function that will be executed after the physics step
  70056. */
  70057. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  70058. this._onAfterPhysicsStepCallbacks.push(func);
  70059. };
  70060. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  70061. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  70062. if (index > -1) {
  70063. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  70064. }
  70065. else {
  70066. BABYLON.Tools.Warn("Function to remove was not found");
  70067. }
  70068. };
  70069. /**
  70070. * register a function that will be executed when this impostor collides against a different body.
  70071. */
  70072. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  70073. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70074. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  70075. };
  70076. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  70077. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70078. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  70079. if (index > -1) {
  70080. this._onPhysicsCollideCallbacks.splice(index, 1);
  70081. }
  70082. else {
  70083. BABYLON.Tools.Warn("Function to remove was not found");
  70084. }
  70085. };
  70086. PhysicsImpostor.prototype.getParentsRotation = function () {
  70087. var parent = this.object.parent;
  70088. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  70089. while (parent) {
  70090. if (parent.rotationQuaternion) {
  70091. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  70092. }
  70093. else {
  70094. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  70095. }
  70096. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  70097. parent = parent.parent;
  70098. }
  70099. return this._tmpQuat;
  70100. };
  70101. /**
  70102. * Apply a force
  70103. */
  70104. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  70105. if (this._physicsEngine) {
  70106. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  70107. }
  70108. return this;
  70109. };
  70110. /**
  70111. * Apply an impulse
  70112. */
  70113. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  70114. if (this._physicsEngine) {
  70115. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  70116. }
  70117. return this;
  70118. };
  70119. /**
  70120. * A help function to create a joint.
  70121. */
  70122. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  70123. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  70124. this.addJoint(otherImpostor, joint);
  70125. return this;
  70126. };
  70127. /**
  70128. * Add a joint to this impostor with a different impostor.
  70129. */
  70130. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  70131. this._joints.push({
  70132. otherImpostor: otherImpostor,
  70133. joint: joint
  70134. });
  70135. if (this._physicsEngine) {
  70136. this._physicsEngine.addJoint(this, otherImpostor, joint);
  70137. }
  70138. return this;
  70139. };
  70140. /**
  70141. * Will keep this body still, in a sleep mode.
  70142. */
  70143. PhysicsImpostor.prototype.sleep = function () {
  70144. if (this._physicsEngine) {
  70145. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  70146. }
  70147. return this;
  70148. };
  70149. /**
  70150. * Wake the body up.
  70151. */
  70152. PhysicsImpostor.prototype.wakeUp = function () {
  70153. if (this._physicsEngine) {
  70154. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  70155. }
  70156. return this;
  70157. };
  70158. PhysicsImpostor.prototype.clone = function (newObject) {
  70159. if (!newObject)
  70160. return null;
  70161. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  70162. };
  70163. PhysicsImpostor.prototype.dispose = function () {
  70164. var _this = this;
  70165. //no dispose if no physics engine is available.
  70166. if (!this._physicsEngine) {
  70167. return;
  70168. }
  70169. this._joints.forEach(function (j) {
  70170. if (_this._physicsEngine) {
  70171. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  70172. }
  70173. });
  70174. //dispose the physics body
  70175. this._physicsEngine.removeImpostor(this);
  70176. if (this.parent) {
  70177. this.parent.forceUpdate();
  70178. }
  70179. else {
  70180. /*this._object.getChildMeshes().forEach(function(mesh) {
  70181. if (mesh.physicsImpostor) {
  70182. if (disposeChildren) {
  70183. mesh.physicsImpostor.dispose();
  70184. mesh.physicsImpostor = null;
  70185. }
  70186. }
  70187. })*/
  70188. }
  70189. this._isDisposed = true;
  70190. };
  70191. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70192. this._deltaPosition.copyFrom(position);
  70193. };
  70194. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70195. if (!this._deltaRotation) {
  70196. this._deltaRotation = new BABYLON.Quaternion();
  70197. }
  70198. this._deltaRotation.copyFrom(rotation);
  70199. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70200. };
  70201. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70202. if (this._physicsEngine) {
  70203. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70204. }
  70205. return this;
  70206. };
  70207. PhysicsImpostor.prototype.getRadius = function () {
  70208. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70209. };
  70210. /**
  70211. * Sync a bone with this impostor
  70212. * @param bone The bone to sync to the impostor.
  70213. * @param boneMesh The mesh that the bone is influencing.
  70214. * @param jointPivot The pivot of the joint / bone in local space.
  70215. * @param distToJoint Optional distance from the impostor to the joint.
  70216. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70217. */
  70218. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70219. var tempVec = PhysicsImpostor._tmpVecs[0];
  70220. var mesh = this.object;
  70221. if (mesh.rotationQuaternion) {
  70222. if (adjustRotation) {
  70223. var tempQuat = PhysicsImpostor._tmpQuat;
  70224. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70225. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70226. }
  70227. else {
  70228. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70229. }
  70230. }
  70231. tempVec.x = 0;
  70232. tempVec.y = 0;
  70233. tempVec.z = 0;
  70234. if (jointPivot) {
  70235. tempVec.x = jointPivot.x;
  70236. tempVec.y = jointPivot.y;
  70237. tempVec.z = jointPivot.z;
  70238. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70239. if (distToJoint === undefined || distToJoint === null) {
  70240. distToJoint = jointPivot.length();
  70241. }
  70242. tempVec.x *= distToJoint;
  70243. tempVec.y *= distToJoint;
  70244. tempVec.z *= distToJoint;
  70245. }
  70246. if (bone.getParent()) {
  70247. tempVec.addInPlace(mesh.getAbsolutePosition());
  70248. bone.setAbsolutePosition(tempVec, boneMesh);
  70249. }
  70250. else {
  70251. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70252. boneMesh.position.x -= tempVec.x;
  70253. boneMesh.position.y -= tempVec.y;
  70254. boneMesh.position.z -= tempVec.z;
  70255. }
  70256. };
  70257. /**
  70258. * Sync impostor to a bone
  70259. * @param bone The bone that the impostor will be synced to.
  70260. * @param boneMesh The mesh that the bone is influencing.
  70261. * @param jointPivot The pivot of the joint / bone in local space.
  70262. * @param distToJoint Optional distance from the impostor to the joint.
  70263. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70264. * @param boneAxis Optional vector3 axis the bone is aligned with
  70265. */
  70266. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70267. var mesh = this.object;
  70268. if (mesh.rotationQuaternion) {
  70269. if (adjustRotation) {
  70270. var tempQuat = PhysicsImpostor._tmpQuat;
  70271. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70272. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70273. }
  70274. else {
  70275. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70276. }
  70277. }
  70278. var pos = PhysicsImpostor._tmpVecs[0];
  70279. var boneDir = PhysicsImpostor._tmpVecs[1];
  70280. if (!boneAxis) {
  70281. boneAxis = PhysicsImpostor._tmpVecs[2];
  70282. boneAxis.x = 0;
  70283. boneAxis.y = 1;
  70284. boneAxis.z = 0;
  70285. }
  70286. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70287. bone.getAbsolutePositionToRef(boneMesh, pos);
  70288. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70289. distToJoint = jointPivot.length();
  70290. }
  70291. if (distToJoint !== undefined && distToJoint !== null) {
  70292. pos.x += boneDir.x * distToJoint;
  70293. pos.y += boneDir.y * distToJoint;
  70294. pos.z += boneDir.z * distToJoint;
  70295. }
  70296. mesh.setAbsolutePosition(pos);
  70297. };
  70298. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70299. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70300. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70301. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70302. //Impostor types
  70303. PhysicsImpostor.NoImpostor = 0;
  70304. PhysicsImpostor.SphereImpostor = 1;
  70305. PhysicsImpostor.BoxImpostor = 2;
  70306. PhysicsImpostor.PlaneImpostor = 3;
  70307. PhysicsImpostor.MeshImpostor = 4;
  70308. PhysicsImpostor.CylinderImpostor = 7;
  70309. PhysicsImpostor.ParticleImpostor = 8;
  70310. PhysicsImpostor.HeightmapImpostor = 9;
  70311. return PhysicsImpostor;
  70312. }());
  70313. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70314. })(BABYLON || (BABYLON = {}));
  70315. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70316. var BABYLON;
  70317. (function (BABYLON) {
  70318. var PhysicsEngine = /** @class */ (function () {
  70319. function PhysicsEngine(gravity, _physicsPlugin) {
  70320. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70321. this._physicsPlugin = _physicsPlugin;
  70322. //new methods and parameters
  70323. this._impostors = [];
  70324. this._joints = [];
  70325. if (!this._physicsPlugin.isSupported()) {
  70326. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70327. + "Please make sure it is included.");
  70328. }
  70329. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70330. this.setGravity(gravity);
  70331. this.setTimeStep();
  70332. }
  70333. PhysicsEngine.prototype.setGravity = function (gravity) {
  70334. this.gravity = gravity;
  70335. this._physicsPlugin.setGravity(this.gravity);
  70336. };
  70337. /**
  70338. * Set the time step of the physics engine.
  70339. * default is 1/60.
  70340. * To slow it down, enter 1/600 for example.
  70341. * To speed it up, 1/30
  70342. * @param {number} newTimeStep the new timestep to apply to this world.
  70343. */
  70344. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70345. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70346. this._physicsPlugin.setTimeStep(newTimeStep);
  70347. };
  70348. /**
  70349. * Get the time step of the physics engine.
  70350. */
  70351. PhysicsEngine.prototype.getTimeStep = function () {
  70352. return this._physicsPlugin.getTimeStep();
  70353. };
  70354. PhysicsEngine.prototype.dispose = function () {
  70355. this._impostors.forEach(function (impostor) {
  70356. impostor.dispose();
  70357. });
  70358. this._physicsPlugin.dispose();
  70359. };
  70360. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70361. return this._physicsPlugin.name;
  70362. };
  70363. /**
  70364. * Adding a new impostor for the impostor tracking.
  70365. * This will be done by the impostor itself.
  70366. * @param {PhysicsImpostor} impostor the impostor to add
  70367. */
  70368. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70369. impostor.uniqueId = this._impostors.push(impostor);
  70370. //if no parent, generate the body
  70371. if (!impostor.parent) {
  70372. this._physicsPlugin.generatePhysicsBody(impostor);
  70373. }
  70374. };
  70375. /**
  70376. * Remove an impostor from the engine.
  70377. * This impostor and its mesh will not longer be updated by the physics engine.
  70378. * @param {PhysicsImpostor} impostor the impostor to remove
  70379. */
  70380. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70381. var index = this._impostors.indexOf(impostor);
  70382. if (index > -1) {
  70383. var removed = this._impostors.splice(index, 1);
  70384. //Is it needed?
  70385. if (removed.length) {
  70386. //this will also remove it from the world.
  70387. removed[0].physicsBody = null;
  70388. }
  70389. }
  70390. };
  70391. /**
  70392. * Add a joint to the physics engine
  70393. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70394. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70395. * @param {PhysicsJoint} the joint that will connect both impostors.
  70396. */
  70397. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70398. var impostorJoint = {
  70399. mainImpostor: mainImpostor,
  70400. connectedImpostor: connectedImpostor,
  70401. joint: joint
  70402. };
  70403. joint.physicsPlugin = this._physicsPlugin;
  70404. this._joints.push(impostorJoint);
  70405. this._physicsPlugin.generateJoint(impostorJoint);
  70406. };
  70407. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  70408. var matchingJoints = this._joints.filter(function (impostorJoint) {
  70409. return (impostorJoint.connectedImpostor === connectedImpostor
  70410. && impostorJoint.joint === joint
  70411. && impostorJoint.mainImpostor === mainImpostor);
  70412. });
  70413. if (matchingJoints.length) {
  70414. this._physicsPlugin.removeJoint(matchingJoints[0]);
  70415. //TODO remove it from the list as well
  70416. }
  70417. };
  70418. /**
  70419. * Called by the scene. no need to call it.
  70420. */
  70421. PhysicsEngine.prototype._step = function (delta) {
  70422. var _this = this;
  70423. //check if any mesh has no body / requires an update
  70424. this._impostors.forEach(function (impostor) {
  70425. if (impostor.isBodyInitRequired()) {
  70426. _this._physicsPlugin.generatePhysicsBody(impostor);
  70427. }
  70428. });
  70429. if (delta > 0.1) {
  70430. delta = 0.1;
  70431. }
  70432. else if (delta <= 0) {
  70433. delta = 1.0 / 60.0;
  70434. }
  70435. this._physicsPlugin.executeStep(delta, this._impostors);
  70436. };
  70437. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  70438. return this._physicsPlugin;
  70439. };
  70440. PhysicsEngine.prototype.getImpostors = function () {
  70441. return this._impostors;
  70442. };
  70443. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  70444. for (var i = 0; i < this._impostors.length; ++i) {
  70445. if (this._impostors[i].object === object) {
  70446. return this._impostors[i];
  70447. }
  70448. }
  70449. return null;
  70450. };
  70451. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  70452. for (var i = 0; i < this._impostors.length; ++i) {
  70453. if (this._impostors[i].physicsBody === body) {
  70454. return this._impostors[i];
  70455. }
  70456. }
  70457. return null;
  70458. };
  70459. // Statics
  70460. PhysicsEngine.Epsilon = 0.001;
  70461. return PhysicsEngine;
  70462. }());
  70463. BABYLON.PhysicsEngine = PhysicsEngine;
  70464. })(BABYLON || (BABYLON = {}));
  70465. //# sourceMappingURL=babylon.physicsEngine.js.map
  70466. var BABYLON;
  70467. (function (BABYLON) {
  70468. var PhysicsHelper = /** @class */ (function () {
  70469. function PhysicsHelper(scene) {
  70470. this._scene = scene;
  70471. this._physicsEngine = this._scene.getPhysicsEngine();
  70472. if (!this._physicsEngine) {
  70473. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  70474. }
  70475. }
  70476. /**
  70477. * @param {Vector3} origin the origin of the explosion
  70478. * @param {number} radius the explosion radius
  70479. * @param {number} strength the explosion strength
  70480. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70481. */
  70482. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  70483. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70484. if (!this._physicsEngine) {
  70485. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  70486. return null;
  70487. }
  70488. var impostors = this._physicsEngine.getImpostors();
  70489. if (impostors.length === 0) {
  70490. return null;
  70491. }
  70492. var event = new PhysicsRadialExplosionEvent(this._scene);
  70493. impostors.forEach(function (impostor) {
  70494. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70495. if (!impostorForceAndContactPoint) {
  70496. return;
  70497. }
  70498. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70499. });
  70500. event.dispose(false);
  70501. return event;
  70502. };
  70503. /**
  70504. * @param {Vector3} origin the origin of the explosion
  70505. * @param {number} radius the explosion radius
  70506. * @param {number} strength the explosion strength
  70507. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70508. */
  70509. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  70510. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70511. if (!this._physicsEngine) {
  70512. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70513. return null;
  70514. }
  70515. var impostors = this._physicsEngine.getImpostors();
  70516. if (impostors.length === 0) {
  70517. return null;
  70518. }
  70519. var event = new PhysicsRadialExplosionEvent(this._scene);
  70520. impostors.forEach(function (impostor) {
  70521. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70522. if (!impostorForceAndContactPoint) {
  70523. return;
  70524. }
  70525. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70526. });
  70527. event.dispose(false);
  70528. return event;
  70529. };
  70530. /**
  70531. * @param {Vector3} origin the origin of the explosion
  70532. * @param {number} radius the explosion radius
  70533. * @param {number} strength the explosion strength
  70534. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70535. */
  70536. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  70537. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70538. if (!this._physicsEngine) {
  70539. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70540. return null;
  70541. }
  70542. var impostors = this._physicsEngine.getImpostors();
  70543. if (impostors.length === 0) {
  70544. return null;
  70545. }
  70546. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  70547. event.dispose(false);
  70548. return event;
  70549. };
  70550. /**
  70551. * @param {Vector3} origin the origin of the updraft
  70552. * @param {number} radius the radius of the updraft
  70553. * @param {number} strength the strength of the updraft
  70554. * @param {number} height the height of the updraft
  70555. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  70556. */
  70557. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  70558. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  70559. if (!this._physicsEngine) {
  70560. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70561. return null;
  70562. }
  70563. if (this._physicsEngine.getImpostors().length === 0) {
  70564. return null;
  70565. }
  70566. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  70567. event.dispose(false);
  70568. return event;
  70569. };
  70570. /**
  70571. * @param {Vector3} origin the of the vortex
  70572. * @param {number} radius the radius of the vortex
  70573. * @param {number} strength the strength of the vortex
  70574. * @param {number} height the height of the vortex
  70575. */
  70576. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  70577. if (!this._physicsEngine) {
  70578. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70579. return null;
  70580. }
  70581. if (this._physicsEngine.getImpostors().length === 0) {
  70582. return null;
  70583. }
  70584. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  70585. event.dispose(false);
  70586. return event;
  70587. };
  70588. return PhysicsHelper;
  70589. }());
  70590. BABYLON.PhysicsHelper = PhysicsHelper;
  70591. /***** Radial explosion *****/
  70592. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  70593. function PhysicsRadialExplosionEvent(scene) {
  70594. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  70595. this._rays = [];
  70596. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  70597. this._scene = scene;
  70598. }
  70599. /**
  70600. * Returns the data related to the radial explosion event (sphere & rays).
  70601. * @returns {PhysicsRadialExplosionEventData}
  70602. */
  70603. PhysicsRadialExplosionEvent.prototype.getData = function () {
  70604. this._dataFetched = true;
  70605. return {
  70606. sphere: this._sphere,
  70607. rays: this._rays,
  70608. };
  70609. };
  70610. /**
  70611. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  70612. * @param impostor
  70613. * @param {Vector3} origin the origin of the explosion
  70614. * @param {number} radius the explosion radius
  70615. * @param {number} strength the explosion strength
  70616. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  70617. * @returns {Nullable<PhysicsForceAndContactPoint>}
  70618. */
  70619. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  70620. if (impostor.mass === 0) {
  70621. return null;
  70622. }
  70623. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  70624. return null;
  70625. }
  70626. if (impostor.object.getClassName() !== 'Mesh') {
  70627. return null;
  70628. }
  70629. var impostorObject = impostor.object;
  70630. var impostorObjectCenter = impostor.getObjectCenter();
  70631. var direction = impostorObjectCenter.subtract(origin);
  70632. var ray = new BABYLON.Ray(origin, direction, radius);
  70633. this._rays.push(ray);
  70634. var hit = ray.intersectsMesh(impostorObject);
  70635. var contactPoint = hit.pickedPoint;
  70636. if (!contactPoint) {
  70637. return null;
  70638. }
  70639. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  70640. if (distanceFromOrigin > radius) {
  70641. return null;
  70642. }
  70643. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  70644. ? strength
  70645. : strength * (1 - (distanceFromOrigin / radius));
  70646. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70647. return { force: force, contactPoint: contactPoint };
  70648. };
  70649. /**
  70650. * Disposes the sphere.
  70651. * @param {bolean} force
  70652. */
  70653. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  70654. var _this = this;
  70655. if (force === void 0) { force = true; }
  70656. if (force) {
  70657. this._sphere.dispose();
  70658. }
  70659. else {
  70660. setTimeout(function () {
  70661. if (!_this._dataFetched) {
  70662. _this._sphere.dispose();
  70663. }
  70664. }, 0);
  70665. }
  70666. };
  70667. /*** Helpers ***/
  70668. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  70669. if (!this._sphere) {
  70670. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  70671. this._sphere.isVisible = false;
  70672. }
  70673. };
  70674. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  70675. var impostorObject = impostor.object;
  70676. this._prepareSphere();
  70677. this._sphere.position = origin;
  70678. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  70679. this._sphere._updateBoundingInfo();
  70680. this._sphere.computeWorldMatrix(true);
  70681. return this._sphere.intersectsMesh(impostorObject, true);
  70682. };
  70683. return PhysicsRadialExplosionEvent;
  70684. }());
  70685. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  70686. /***** Gravitational Field *****/
  70687. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  70688. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  70689. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70690. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70691. this._physicsHelper = physicsHelper;
  70692. this._scene = scene;
  70693. this._origin = origin;
  70694. this._radius = radius;
  70695. this._strength = strength;
  70696. this._falloff = falloff;
  70697. this._tickCallback = this._tick.bind(this);
  70698. }
  70699. /**
  70700. * Returns the data related to the gravitational field event (sphere).
  70701. * @returns {PhysicsGravitationalFieldEventData}
  70702. */
  70703. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  70704. this._dataFetched = true;
  70705. return {
  70706. sphere: this._sphere,
  70707. };
  70708. };
  70709. /**
  70710. * Enables the gravitational field.
  70711. */
  70712. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  70713. this._tickCallback.call(this);
  70714. this._scene.registerBeforeRender(this._tickCallback);
  70715. };
  70716. /**
  70717. * Disables the gravitational field.
  70718. */
  70719. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  70720. this._scene.unregisterBeforeRender(this._tickCallback);
  70721. };
  70722. /**
  70723. * Disposes the sphere.
  70724. * @param {bolean} force
  70725. */
  70726. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  70727. var _this = this;
  70728. if (force === void 0) { force = true; }
  70729. if (force) {
  70730. this._sphere.dispose();
  70731. }
  70732. else {
  70733. setTimeout(function () {
  70734. if (!_this._dataFetched) {
  70735. _this._sphere.dispose();
  70736. }
  70737. }, 0);
  70738. }
  70739. };
  70740. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  70741. // Since the params won't change, we fetch the event only once
  70742. if (this._sphere) {
  70743. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70744. }
  70745. else {
  70746. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70747. if (radialExplosionEvent) {
  70748. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  70749. }
  70750. }
  70751. };
  70752. return PhysicsGravitationalFieldEvent;
  70753. }());
  70754. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  70755. /***** Updraft *****/
  70756. var PhysicsUpdraftEvent = /** @class */ (function () {
  70757. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  70758. this._scene = _scene;
  70759. this._origin = _origin;
  70760. this._radius = _radius;
  70761. this._strength = _strength;
  70762. this._height = _height;
  70763. this._updraftMode = _updraftMode;
  70764. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70765. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  70766. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70767. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70768. this._physicsEngine = this._scene.getPhysicsEngine();
  70769. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70770. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70771. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70772. this._originDirection = this._origin.subtract(this._originTop).normalize();
  70773. }
  70774. this._tickCallback = this._tick.bind(this);
  70775. }
  70776. /**
  70777. * Returns the data related to the updraft event (cylinder).
  70778. * @returns {PhysicsUpdraftEventData}
  70779. */
  70780. PhysicsUpdraftEvent.prototype.getData = function () {
  70781. this._dataFetched = true;
  70782. return {
  70783. cylinder: this._cylinder,
  70784. };
  70785. };
  70786. /**
  70787. * Enables the updraft.
  70788. */
  70789. PhysicsUpdraftEvent.prototype.enable = function () {
  70790. this._tickCallback.call(this);
  70791. this._scene.registerBeforeRender(this._tickCallback);
  70792. };
  70793. /**
  70794. * Disables the cortex.
  70795. */
  70796. PhysicsUpdraftEvent.prototype.disable = function () {
  70797. this._scene.unregisterBeforeRender(this._tickCallback);
  70798. };
  70799. /**
  70800. * Disposes the sphere.
  70801. * @param {bolean} force
  70802. */
  70803. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  70804. var _this = this;
  70805. if (force === void 0) { force = true; }
  70806. if (force) {
  70807. this._cylinder.dispose();
  70808. }
  70809. else {
  70810. setTimeout(function () {
  70811. if (!_this._dataFetched) {
  70812. _this._cylinder.dispose();
  70813. }
  70814. }, 0);
  70815. }
  70816. };
  70817. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70818. if (impostor.mass === 0) {
  70819. return null;
  70820. }
  70821. if (!this._intersectsWithCylinder(impostor)) {
  70822. return null;
  70823. }
  70824. var impostorObjectCenter = impostor.getObjectCenter();
  70825. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70826. var direction = this._originDirection;
  70827. }
  70828. else {
  70829. var direction = impostorObjectCenter.subtract(this._originTop);
  70830. }
  70831. var multiplier = this._strength * -1;
  70832. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70833. return { force: force, contactPoint: impostorObjectCenter };
  70834. };
  70835. PhysicsUpdraftEvent.prototype._tick = function () {
  70836. var _this = this;
  70837. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70838. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70839. if (!impostorForceAndContactPoint) {
  70840. return;
  70841. }
  70842. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70843. });
  70844. };
  70845. /*** Helpers ***/
  70846. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  70847. if (!this._cylinder) {
  70848. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  70849. height: this._height,
  70850. diameter: this._radius * 2,
  70851. }, this._scene);
  70852. this._cylinder.isVisible = false;
  70853. }
  70854. };
  70855. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  70856. var impostorObject = impostor.object;
  70857. this._prepareCylinder();
  70858. this._cylinder.position = this._cylinderPosition;
  70859. return this._cylinder.intersectsMesh(impostorObject, true);
  70860. };
  70861. return PhysicsUpdraftEvent;
  70862. }());
  70863. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  70864. /***** Vortex *****/
  70865. var PhysicsVortexEvent = /** @class */ (function () {
  70866. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  70867. this._scene = _scene;
  70868. this._origin = _origin;
  70869. this._radius = _radius;
  70870. this._strength = _strength;
  70871. this._height = _height;
  70872. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70873. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  70874. this._updraftMultiplier = 0.02;
  70875. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70876. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70877. this._physicsEngine = this._scene.getPhysicsEngine();
  70878. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70879. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70880. this._tickCallback = this._tick.bind(this);
  70881. }
  70882. /**
  70883. * Returns the data related to the vortex event (cylinder).
  70884. * @returns {PhysicsVortexEventData}
  70885. */
  70886. PhysicsVortexEvent.prototype.getData = function () {
  70887. this._dataFetched = true;
  70888. return {
  70889. cylinder: this._cylinder,
  70890. };
  70891. };
  70892. /**
  70893. * Enables the vortex.
  70894. */
  70895. PhysicsVortexEvent.prototype.enable = function () {
  70896. this._tickCallback.call(this);
  70897. this._scene.registerBeforeRender(this._tickCallback);
  70898. };
  70899. /**
  70900. * Disables the cortex.
  70901. */
  70902. PhysicsVortexEvent.prototype.disable = function () {
  70903. this._scene.unregisterBeforeRender(this._tickCallback);
  70904. };
  70905. /**
  70906. * Disposes the sphere.
  70907. * @param {bolean} force
  70908. */
  70909. PhysicsVortexEvent.prototype.dispose = function (force) {
  70910. var _this = this;
  70911. if (force === void 0) { force = true; }
  70912. if (force) {
  70913. this._cylinder.dispose();
  70914. }
  70915. else {
  70916. setTimeout(function () {
  70917. if (!_this._dataFetched) {
  70918. _this._cylinder.dispose();
  70919. }
  70920. }, 0);
  70921. }
  70922. };
  70923. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70924. if (impostor.mass === 0) {
  70925. return null;
  70926. }
  70927. if (!this._intersectsWithCylinder(impostor)) {
  70928. return null;
  70929. }
  70930. if (impostor.object.getClassName() !== 'Mesh') {
  70931. return null;
  70932. }
  70933. var impostorObject = impostor.object;
  70934. var impostorObjectCenter = impostor.getObjectCenter();
  70935. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  70936. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  70937. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  70938. var hit = ray.intersectsMesh(impostorObject);
  70939. var contactPoint = hit.pickedPoint;
  70940. if (!contactPoint) {
  70941. return null;
  70942. }
  70943. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  70944. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  70945. var directionToOrigin = contactPoint.normalize();
  70946. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70947. directionToOrigin = directionToOrigin.negate();
  70948. }
  70949. // TODO: find a more physically based solution
  70950. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70951. var forceX = directionToOrigin.x * this._strength / 8;
  70952. var forceY = directionToOrigin.y * this._updraftMultiplier;
  70953. var forceZ = directionToOrigin.z * this._strength / 8;
  70954. }
  70955. else {
  70956. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  70957. var forceY = this._originTop.y * this._updraftMultiplier;
  70958. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  70959. }
  70960. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  70961. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  70962. return { force: force, contactPoint: impostorObjectCenter };
  70963. };
  70964. PhysicsVortexEvent.prototype._tick = function () {
  70965. var _this = this;
  70966. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70967. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70968. if (!impostorForceAndContactPoint) {
  70969. return;
  70970. }
  70971. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70972. });
  70973. };
  70974. /*** Helpers ***/
  70975. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  70976. if (!this._cylinder) {
  70977. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  70978. height: this._height,
  70979. diameter: this._radius * 2,
  70980. }, this._scene);
  70981. this._cylinder.isVisible = false;
  70982. }
  70983. };
  70984. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  70985. var impostorObject = impostor.object;
  70986. this._prepareCylinder();
  70987. this._cylinder.position = this._cylinderPosition;
  70988. return this._cylinder.intersectsMesh(impostorObject, true);
  70989. };
  70990. return PhysicsVortexEvent;
  70991. }());
  70992. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  70993. /***** Enums *****/
  70994. /**
  70995. * The strenght of the force in correspondence to the distance of the affected object
  70996. */
  70997. var PhysicsRadialImpulseFalloff;
  70998. (function (PhysicsRadialImpulseFalloff) {
  70999. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  71000. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  71001. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  71002. /**
  71003. * The strenght of the force in correspondence to the distance of the affected object
  71004. */
  71005. var PhysicsUpdraftMode;
  71006. (function (PhysicsUpdraftMode) {
  71007. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  71008. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  71009. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  71010. })(BABYLON || (BABYLON = {}));
  71011. //# sourceMappingURL=babylon.physicsHelper.js.map
  71012. var BABYLON;
  71013. (function (BABYLON) {
  71014. var CannonJSPlugin = /** @class */ (function () {
  71015. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  71016. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  71017. if (iterations === void 0) { iterations = 10; }
  71018. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  71019. this.name = "CannonJSPlugin";
  71020. this._physicsMaterials = new Array();
  71021. this._fixedTimeStep = 1 / 60;
  71022. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  71023. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  71024. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  71025. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  71026. this._tmpPosition = BABYLON.Vector3.Zero();
  71027. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  71028. this._tmpUnityRotation = new BABYLON.Quaternion();
  71029. if (!this.isSupported()) {
  71030. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  71031. return;
  71032. }
  71033. this._extendNamespace();
  71034. this.world = new this.BJSCANNON.World();
  71035. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  71036. this.world.solver.iterations = iterations;
  71037. }
  71038. CannonJSPlugin.prototype.setGravity = function (gravity) {
  71039. this.world.gravity.copy(gravity);
  71040. };
  71041. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  71042. this._fixedTimeStep = timeStep;
  71043. };
  71044. CannonJSPlugin.prototype.getTimeStep = function () {
  71045. return this._fixedTimeStep;
  71046. };
  71047. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  71048. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  71049. };
  71050. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71051. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71052. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71053. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  71054. };
  71055. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71056. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71057. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71058. impostor.physicsBody.applyForce(impulse, worldPoint);
  71059. };
  71060. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71061. //parent-child relationship. Does this impostor has a parent impostor?
  71062. if (impostor.parent) {
  71063. if (impostor.physicsBody) {
  71064. this.removePhysicsBody(impostor);
  71065. //TODO is that needed?
  71066. impostor.forceUpdate();
  71067. }
  71068. return;
  71069. }
  71070. //should a new body be created for this impostor?
  71071. if (impostor.isBodyInitRequired()) {
  71072. var shape = this._createShape(impostor);
  71073. //unregister events, if body is being changed
  71074. var oldBody = impostor.physicsBody;
  71075. if (oldBody) {
  71076. this.removePhysicsBody(impostor);
  71077. }
  71078. //create the body and material
  71079. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  71080. var bodyCreationObject = {
  71081. mass: impostor.getParam("mass"),
  71082. material: material
  71083. };
  71084. // A simple extend, in case native options were used.
  71085. var nativeOptions = impostor.getParam("nativeOptions");
  71086. for (var key in nativeOptions) {
  71087. if (nativeOptions.hasOwnProperty(key)) {
  71088. bodyCreationObject[key] = nativeOptions[key];
  71089. }
  71090. }
  71091. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  71092. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  71093. this.world.addEventListener("preStep", impostor.beforeStep);
  71094. this.world.addEventListener("postStep", impostor.afterStep);
  71095. impostor.physicsBody.addShape(shape);
  71096. this.world.add(impostor.physicsBody);
  71097. //try to keep the body moving in the right direction by taking old properties.
  71098. //Should be tested!
  71099. if (oldBody) {
  71100. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  71101. impostor.physicsBody[param].copy(oldBody[param]);
  71102. });
  71103. }
  71104. this._processChildMeshes(impostor);
  71105. }
  71106. //now update the body's transformation
  71107. this._updatePhysicsBodyTransformation(impostor);
  71108. };
  71109. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  71110. var _this = this;
  71111. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  71112. var currentRotation = mainImpostor.object.rotationQuaternion;
  71113. if (meshChildren.length) {
  71114. var processMesh = function (localPosition, mesh) {
  71115. if (!currentRotation || !mesh.rotationQuaternion) {
  71116. return;
  71117. }
  71118. var childImpostor = mesh.getPhysicsImpostor();
  71119. if (childImpostor) {
  71120. var parent = childImpostor.parent;
  71121. if (parent !== mainImpostor) {
  71122. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  71123. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  71124. if (childImpostor.physicsBody) {
  71125. _this.removePhysicsBody(childImpostor);
  71126. childImpostor.physicsBody = null;
  71127. }
  71128. childImpostor.parent = mainImpostor;
  71129. childImpostor.resetUpdateFlags();
  71130. 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));
  71131. //Add the mass of the children.
  71132. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  71133. }
  71134. }
  71135. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  71136. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  71137. };
  71138. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  71139. }
  71140. };
  71141. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71142. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  71143. this.world.removeEventListener("preStep", impostor.beforeStep);
  71144. this.world.removeEventListener("postStep", impostor.afterStep);
  71145. this.world.remove(impostor.physicsBody);
  71146. };
  71147. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71148. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71149. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71150. if (!mainBody || !connectedBody) {
  71151. return;
  71152. }
  71153. var constraint;
  71154. var jointData = impostorJoint.joint.jointData;
  71155. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  71156. var constraintData = {
  71157. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  71158. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  71159. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  71160. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  71161. maxForce: jointData.nativeParams.maxForce,
  71162. collideConnected: !!jointData.collision
  71163. };
  71164. switch (impostorJoint.joint.type) {
  71165. case BABYLON.PhysicsJoint.HingeJoint:
  71166. case BABYLON.PhysicsJoint.Hinge2Joint:
  71167. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  71168. break;
  71169. case BABYLON.PhysicsJoint.DistanceJoint:
  71170. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  71171. break;
  71172. case BABYLON.PhysicsJoint.SpringJoint:
  71173. var springData = jointData;
  71174. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  71175. restLength: springData.length,
  71176. stiffness: springData.stiffness,
  71177. damping: springData.damping,
  71178. localAnchorA: constraintData.pivotA,
  71179. localAnchorB: constraintData.pivotB
  71180. });
  71181. break;
  71182. case BABYLON.PhysicsJoint.LockJoint:
  71183. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71184. break;
  71185. case BABYLON.PhysicsJoint.PointToPointJoint:
  71186. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71187. default:
  71188. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71189. break;
  71190. }
  71191. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71192. constraint.collideConnected = !!jointData.collision;
  71193. impostorJoint.joint.physicsJoint = constraint;
  71194. //don't add spring as constraint, as it is not one.
  71195. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71196. this.world.addConstraint(constraint);
  71197. }
  71198. else {
  71199. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71200. constraint.applyForce();
  71201. });
  71202. }
  71203. };
  71204. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71205. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71206. };
  71207. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71208. var index;
  71209. var mat;
  71210. for (index = 0; index < this._physicsMaterials.length; index++) {
  71211. mat = this._physicsMaterials[index];
  71212. if (mat.friction === friction && mat.restitution === restitution) {
  71213. return mat;
  71214. }
  71215. }
  71216. var currentMat = new this.BJSCANNON.Material(name);
  71217. currentMat.friction = friction;
  71218. currentMat.restitution = restitution;
  71219. this._physicsMaterials.push(currentMat);
  71220. return currentMat;
  71221. };
  71222. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71223. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71224. };
  71225. CannonJSPlugin.prototype._createShape = function (impostor) {
  71226. var object = impostor.object;
  71227. var returnValue;
  71228. var extendSize = impostor.getObjectExtendSize();
  71229. switch (impostor.type) {
  71230. case BABYLON.PhysicsImpostor.SphereImpostor:
  71231. var radiusX = extendSize.x;
  71232. var radiusY = extendSize.y;
  71233. var radiusZ = extendSize.z;
  71234. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71235. break;
  71236. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71237. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71238. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71239. break;
  71240. case BABYLON.PhysicsImpostor.BoxImpostor:
  71241. var box = extendSize.scale(0.5);
  71242. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71243. break;
  71244. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71245. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71246. returnValue = new this.BJSCANNON.Plane();
  71247. break;
  71248. case BABYLON.PhysicsImpostor.MeshImpostor:
  71249. // should transform the vertex data to world coordinates!!
  71250. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71251. var rawFaces = object.getIndices ? object.getIndices() : [];
  71252. if (!rawVerts)
  71253. return;
  71254. // get only scale! so the object could transform correctly.
  71255. var oldPosition = object.position.clone();
  71256. var oldRotation = object.rotation && object.rotation.clone();
  71257. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71258. object.position.copyFromFloats(0, 0, 0);
  71259. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71260. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71261. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71262. var transform = object.computeWorldMatrix(true);
  71263. // convert rawVerts to object space
  71264. var temp = new Array();
  71265. var index;
  71266. for (index = 0; index < rawVerts.length; index += 3) {
  71267. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71268. }
  71269. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71270. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71271. //now set back the transformation!
  71272. object.position.copyFrom(oldPosition);
  71273. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71274. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71275. break;
  71276. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71277. var oldPosition2 = object.position.clone();
  71278. var oldRotation2 = object.rotation && object.rotation.clone();
  71279. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71280. object.position.copyFromFloats(0, 0, 0);
  71281. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71282. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71283. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71284. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71285. returnValue = this._createHeightmap(object);
  71286. object.position.copyFrom(oldPosition2);
  71287. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71288. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71289. object.computeWorldMatrix(true);
  71290. break;
  71291. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71292. returnValue = new this.BJSCANNON.Particle();
  71293. break;
  71294. }
  71295. return returnValue;
  71296. };
  71297. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71298. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71299. var transform = object.computeWorldMatrix(true);
  71300. // convert rawVerts to object space
  71301. var temp = new Array();
  71302. var index;
  71303. for (index = 0; index < pos.length; index += 3) {
  71304. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71305. }
  71306. pos = temp;
  71307. var matrix = new Array();
  71308. //For now pointDepth will not be used and will be automatically calculated.
  71309. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71310. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71311. var boundingInfo = object.getBoundingInfo();
  71312. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71313. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71314. var elementSize = dim * 2 / arraySize;
  71315. for (var i = 0; i < pos.length; i = i + 3) {
  71316. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71317. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71318. var y = -pos[i + 2] + minY;
  71319. if (!matrix[x]) {
  71320. matrix[x] = [];
  71321. }
  71322. if (!matrix[x][z]) {
  71323. matrix[x][z] = y;
  71324. }
  71325. matrix[x][z] = Math.max(y, matrix[x][z]);
  71326. }
  71327. for (var x = 0; x <= arraySize; ++x) {
  71328. if (!matrix[x]) {
  71329. var loc = 1;
  71330. while (!matrix[(x + loc) % arraySize]) {
  71331. loc++;
  71332. }
  71333. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71334. //console.log("missing x", x);
  71335. }
  71336. for (var z = 0; z <= arraySize; ++z) {
  71337. if (!matrix[x][z]) {
  71338. var loc = 1;
  71339. var newValue;
  71340. while (newValue === undefined) {
  71341. newValue = matrix[x][(z + loc++) % arraySize];
  71342. }
  71343. matrix[x][z] = newValue;
  71344. }
  71345. }
  71346. }
  71347. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71348. elementSize: elementSize
  71349. });
  71350. //For future reference, needed for body transformation
  71351. shape.minY = minY;
  71352. return shape;
  71353. };
  71354. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71355. var object = impostor.object;
  71356. //make sure it is updated...
  71357. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71358. // The delta between the mesh position and the mesh bounding box center
  71359. var bInfo = object.getBoundingInfo();
  71360. if (!bInfo)
  71361. return;
  71362. var center = impostor.getObjectCenter();
  71363. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71364. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71365. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71366. this._tmpPosition.copyFrom(center);
  71367. var quaternion = object.rotationQuaternion;
  71368. if (!quaternion) {
  71369. return;
  71370. }
  71371. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71372. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71373. //-90 DEG in X, precalculated
  71374. quaternion = quaternion.multiply(this._minus90X);
  71375. //Invert! (Precalculated, 90 deg in X)
  71376. //No need to clone. this will never change.
  71377. impostor.setDeltaRotation(this._plus90X);
  71378. }
  71379. //If it is a heightfield, if should be centered.
  71380. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71381. var mesh = object;
  71382. var boundingInfo = mesh.getBoundingInfo();
  71383. //calculate the correct body position:
  71384. var rotationQuaternion = mesh.rotationQuaternion;
  71385. mesh.rotationQuaternion = this._tmpUnityRotation;
  71386. mesh.computeWorldMatrix(true);
  71387. //get original center with no rotation
  71388. var c = center.clone();
  71389. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71390. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71391. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71392. mesh.setPivotMatrix(p);
  71393. mesh.computeWorldMatrix(true);
  71394. //calculate the translation
  71395. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71396. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71397. //add it inverted to the delta
  71398. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71399. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71400. //rotation is back
  71401. mesh.rotationQuaternion = rotationQuaternion;
  71402. mesh.setPivotMatrix(oldPivot);
  71403. mesh.computeWorldMatrix(true);
  71404. }
  71405. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71406. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71407. //this._tmpPosition.copyFrom(object.position);
  71408. }
  71409. impostor.setDeltaPosition(this._tmpDeltaPosition);
  71410. //Now update the impostor object
  71411. impostor.physicsBody.position.copy(this._tmpPosition);
  71412. impostor.physicsBody.quaternion.copy(quaternion);
  71413. };
  71414. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71415. impostor.object.position.copyFrom(impostor.physicsBody.position);
  71416. if (impostor.object.rotationQuaternion) {
  71417. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  71418. }
  71419. };
  71420. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71421. impostor.physicsBody.position.copy(newPosition);
  71422. impostor.physicsBody.quaternion.copy(newRotation);
  71423. };
  71424. CannonJSPlugin.prototype.isSupported = function () {
  71425. return this.BJSCANNON !== undefined;
  71426. };
  71427. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71428. impostor.physicsBody.velocity.copy(velocity);
  71429. };
  71430. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71431. impostor.physicsBody.angularVelocity.copy(velocity);
  71432. };
  71433. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71434. var v = impostor.physicsBody.velocity;
  71435. if (!v) {
  71436. return null;
  71437. }
  71438. return new BABYLON.Vector3(v.x, v.y, v.z);
  71439. };
  71440. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71441. var v = impostor.physicsBody.angularVelocity;
  71442. if (!v) {
  71443. return null;
  71444. }
  71445. return new BABYLON.Vector3(v.x, v.y, v.z);
  71446. };
  71447. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71448. impostor.physicsBody.mass = mass;
  71449. impostor.physicsBody.updateMassProperties();
  71450. };
  71451. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  71452. return impostor.physicsBody.mass;
  71453. };
  71454. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  71455. return impostor.physicsBody.material.friction;
  71456. };
  71457. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71458. impostor.physicsBody.material.friction = friction;
  71459. };
  71460. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71461. return impostor.physicsBody.material.restitution;
  71462. };
  71463. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71464. impostor.physicsBody.material.restitution = restitution;
  71465. };
  71466. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  71467. impostor.physicsBody.sleep();
  71468. };
  71469. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  71470. impostor.physicsBody.wakeUp();
  71471. };
  71472. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71473. joint.physicsJoint.distance = maxDistance;
  71474. };
  71475. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71476. // if (!motorIndex) {
  71477. // joint.physicsJoint.enableMotor();
  71478. // }
  71479. // }
  71480. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71481. // if (!motorIndex) {
  71482. // joint.physicsJoint.disableMotor();
  71483. // }
  71484. // }
  71485. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71486. if (!motorIndex) {
  71487. joint.physicsJoint.enableMotor();
  71488. joint.physicsJoint.setMotorSpeed(speed);
  71489. if (maxForce) {
  71490. this.setLimit(joint, maxForce);
  71491. }
  71492. }
  71493. };
  71494. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  71495. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  71496. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  71497. };
  71498. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71499. var body = impostor.physicsBody;
  71500. mesh.position.x = body.position.x;
  71501. mesh.position.y = body.position.y;
  71502. mesh.position.z = body.position.z;
  71503. if (mesh.rotationQuaternion) {
  71504. mesh.rotationQuaternion.x = body.quaternion.x;
  71505. mesh.rotationQuaternion.y = body.quaternion.y;
  71506. mesh.rotationQuaternion.z = body.quaternion.z;
  71507. mesh.rotationQuaternion.w = body.quaternion.w;
  71508. }
  71509. };
  71510. CannonJSPlugin.prototype.getRadius = function (impostor) {
  71511. var shape = impostor.physicsBody.shapes[0];
  71512. return shape.boundingSphereRadius;
  71513. };
  71514. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71515. var shape = impostor.physicsBody.shapes[0];
  71516. result.x = shape.halfExtents.x * 2;
  71517. result.y = shape.halfExtents.y * 2;
  71518. result.z = shape.halfExtents.z * 2;
  71519. };
  71520. CannonJSPlugin.prototype.dispose = function () {
  71521. };
  71522. CannonJSPlugin.prototype._extendNamespace = function () {
  71523. //this will force cannon to execute at least one step when using interpolation
  71524. var step_tmp1 = new this.BJSCANNON.Vec3();
  71525. var Engine = this.BJSCANNON;
  71526. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  71527. maxSubSteps = maxSubSteps || 10;
  71528. timeSinceLastCalled = timeSinceLastCalled || 0;
  71529. if (timeSinceLastCalled === 0) {
  71530. this.internalStep(dt);
  71531. this.time += dt;
  71532. }
  71533. else {
  71534. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  71535. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  71536. var t0 = performance.now();
  71537. for (var i = 0; i !== internalSteps; i++) {
  71538. this.internalStep(dt);
  71539. if (performance.now() - t0 > dt * 1000) {
  71540. break;
  71541. }
  71542. }
  71543. this.time += timeSinceLastCalled;
  71544. var h = this.time % dt;
  71545. var h_div_dt = h / dt;
  71546. var interpvelo = step_tmp1;
  71547. var bodies = this.bodies;
  71548. for (var j = 0; j !== bodies.length; j++) {
  71549. var b = bodies[j];
  71550. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  71551. b.position.vsub(b.previousPosition, interpvelo);
  71552. interpvelo.scale(h_div_dt, interpvelo);
  71553. b.position.vadd(interpvelo, b.interpolatedPosition);
  71554. }
  71555. else {
  71556. b.interpolatedPosition.copy(b.position);
  71557. b.interpolatedQuaternion.copy(b.quaternion);
  71558. }
  71559. }
  71560. }
  71561. };
  71562. };
  71563. return CannonJSPlugin;
  71564. }());
  71565. BABYLON.CannonJSPlugin = CannonJSPlugin;
  71566. })(BABYLON || (BABYLON = {}));
  71567. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  71568. var BABYLON;
  71569. (function (BABYLON) {
  71570. var OimoJSPlugin = /** @class */ (function () {
  71571. function OimoJSPlugin(iterations) {
  71572. this.name = "OimoJSPlugin";
  71573. this._tmpImpostorsArray = [];
  71574. this._tmpPositionVector = BABYLON.Vector3.Zero();
  71575. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  71576. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  71577. this.world.worldscale(1);
  71578. this.world.clear();
  71579. //making sure no stats are calculated
  71580. this.world.isNoStat = true;
  71581. }
  71582. OimoJSPlugin.prototype.setGravity = function (gravity) {
  71583. this.world.gravity.copy(gravity);
  71584. };
  71585. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  71586. this.world.timeStep = timeStep;
  71587. };
  71588. OimoJSPlugin.prototype.getTimeStep = function () {
  71589. return this.world.timeStep;
  71590. };
  71591. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  71592. var _this = this;
  71593. impostors.forEach(function (impostor) {
  71594. impostor.beforeStep();
  71595. });
  71596. this.world.step();
  71597. impostors.forEach(function (impostor) {
  71598. impostor.afterStep();
  71599. //update the ordered impostors array
  71600. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  71601. });
  71602. //check for collisions
  71603. var contact = this.world.contacts;
  71604. while (contact !== null) {
  71605. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  71606. contact = contact.next;
  71607. continue;
  71608. }
  71609. //is this body colliding with any other? get the impostor
  71610. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  71611. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  71612. if (!mainImpostor || !collidingImpostor) {
  71613. contact = contact.next;
  71614. continue;
  71615. }
  71616. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  71617. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  71618. contact = contact.next;
  71619. }
  71620. };
  71621. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71622. var mass = impostor.physicsBody.massInfo.mass;
  71623. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  71624. };
  71625. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71626. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  71627. this.applyImpulse(impostor, force, contactPoint);
  71628. };
  71629. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71630. var _this = this;
  71631. //parent-child relationship. Does this impostor has a parent impostor?
  71632. if (impostor.parent) {
  71633. if (impostor.physicsBody) {
  71634. this.removePhysicsBody(impostor);
  71635. //TODO is that needed?
  71636. impostor.forceUpdate();
  71637. }
  71638. return;
  71639. }
  71640. if (impostor.isBodyInitRequired()) {
  71641. var bodyConfig = {
  71642. name: impostor.uniqueId,
  71643. //Oimo must have mass, also for static objects.
  71644. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  71645. size: [],
  71646. type: [],
  71647. pos: [],
  71648. rot: [],
  71649. move: impostor.getParam("mass") !== 0,
  71650. //Supporting older versions of Oimo
  71651. world: this.world
  71652. };
  71653. var impostors = [impostor];
  71654. var addToArray = function (parent) {
  71655. if (!parent.getChildMeshes)
  71656. return;
  71657. parent.getChildMeshes().forEach(function (m) {
  71658. if (m.physicsImpostor) {
  71659. impostors.push(m.physicsImpostor);
  71660. //m.physicsImpostor._init();
  71661. }
  71662. });
  71663. };
  71664. addToArray(impostor.object);
  71665. var checkWithEpsilon_1 = function (value) {
  71666. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  71667. };
  71668. impostors.forEach(function (i) {
  71669. if (!impostor.object.rotationQuaternion) {
  71670. return;
  71671. }
  71672. //get the correct bounding box
  71673. var oldQuaternion = i.object.rotationQuaternion;
  71674. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  71675. x: impostor.object.rotationQuaternion.x,
  71676. y: impostor.object.rotationQuaternion.y,
  71677. z: impostor.object.rotationQuaternion.z,
  71678. s: impostor.object.rotationQuaternion.w
  71679. });
  71680. var extendSize = i.getObjectExtendSize();
  71681. if (i === impostor) {
  71682. var center = impostor.getObjectCenter();
  71683. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  71684. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  71685. //Can also use Array.prototype.push.apply
  71686. bodyConfig.pos.push(center.x);
  71687. bodyConfig.pos.push(center.y);
  71688. bodyConfig.pos.push(center.z);
  71689. //tmp solution
  71690. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71691. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71692. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71693. }
  71694. else {
  71695. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  71696. bodyConfig.pos.push(localPosition.x);
  71697. bodyConfig.pos.push(localPosition.y);
  71698. bodyConfig.pos.push(localPosition.z);
  71699. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  71700. bodyConfig.rot.push(0);
  71701. bodyConfig.rot.push(0);
  71702. bodyConfig.rot.push(0);
  71703. }
  71704. // register mesh
  71705. switch (i.type) {
  71706. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71707. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  71708. case BABYLON.PhysicsImpostor.SphereImpostor:
  71709. var radiusX = extendSize.x;
  71710. var radiusY = extendSize.y;
  71711. var radiusZ = extendSize.z;
  71712. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  71713. bodyConfig.type.push('sphere');
  71714. //due to the way oimo works with compounds, add 3 times
  71715. bodyConfig.size.push(size);
  71716. bodyConfig.size.push(size);
  71717. bodyConfig.size.push(size);
  71718. break;
  71719. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71720. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  71721. var sizeY = checkWithEpsilon_1(extendSize.y);
  71722. bodyConfig.type.push('cylinder');
  71723. bodyConfig.size.push(sizeX);
  71724. bodyConfig.size.push(sizeY);
  71725. //due to the way oimo works with compounds, add one more value.
  71726. bodyConfig.size.push(sizeY);
  71727. break;
  71728. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71729. case BABYLON.PhysicsImpostor.BoxImpostor:
  71730. default:
  71731. var sizeX = checkWithEpsilon_1(extendSize.x);
  71732. var sizeY = checkWithEpsilon_1(extendSize.y);
  71733. var sizeZ = checkWithEpsilon_1(extendSize.z);
  71734. bodyConfig.type.push('box');
  71735. bodyConfig.size.push(sizeX);
  71736. bodyConfig.size.push(sizeY);
  71737. bodyConfig.size.push(sizeZ);
  71738. break;
  71739. }
  71740. //actually not needed, but hey...
  71741. i.object.rotationQuaternion = oldQuaternion;
  71742. });
  71743. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  71744. }
  71745. else {
  71746. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  71747. }
  71748. impostor.setDeltaPosition(this._tmpPositionVector);
  71749. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  71750. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  71751. };
  71752. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71753. //impostor.physicsBody.dispose();
  71754. //Same as : (older oimo versions)
  71755. this.world.removeRigidBody(impostor.physicsBody);
  71756. };
  71757. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71758. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71759. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71760. if (!mainBody || !connectedBody) {
  71761. return;
  71762. }
  71763. var jointData = impostorJoint.joint.jointData;
  71764. var options = jointData.nativeParams || {};
  71765. var type;
  71766. var nativeJointData = {
  71767. body1: mainBody,
  71768. body2: connectedBody,
  71769. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  71770. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  71771. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  71772. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  71773. min: options.min,
  71774. max: options.max,
  71775. collision: options.collision || jointData.collision,
  71776. spring: options.spring,
  71777. //supporting older version of Oimo
  71778. world: this.world
  71779. };
  71780. switch (impostorJoint.joint.type) {
  71781. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71782. type = "jointBall";
  71783. break;
  71784. case BABYLON.PhysicsJoint.SpringJoint:
  71785. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  71786. var springData = jointData;
  71787. nativeJointData.min = springData.length || nativeJointData.min;
  71788. //Max should also be set, just make sure it is at least min
  71789. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  71790. case BABYLON.PhysicsJoint.DistanceJoint:
  71791. type = "jointDistance";
  71792. nativeJointData.max = jointData.maxDistance;
  71793. break;
  71794. case BABYLON.PhysicsJoint.PrismaticJoint:
  71795. type = "jointPrisme";
  71796. break;
  71797. case BABYLON.PhysicsJoint.SliderJoint:
  71798. type = "jointSlide";
  71799. break;
  71800. case BABYLON.PhysicsJoint.WheelJoint:
  71801. type = "jointWheel";
  71802. break;
  71803. case BABYLON.PhysicsJoint.HingeJoint:
  71804. default:
  71805. type = "jointHinge";
  71806. break;
  71807. }
  71808. nativeJointData.type = type;
  71809. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  71810. };
  71811. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71812. //Bug in Oimo prevents us from disposing a joint in the playground
  71813. //joint.joint.physicsJoint.dispose();
  71814. //So we will bruteforce it!
  71815. try {
  71816. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  71817. }
  71818. catch (e) {
  71819. BABYLON.Tools.Warn(e);
  71820. }
  71821. };
  71822. OimoJSPlugin.prototype.isSupported = function () {
  71823. return this.BJSOIMO !== undefined;
  71824. };
  71825. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71826. if (!impostor.physicsBody.sleeping) {
  71827. //TODO check that
  71828. if (impostor.physicsBody.shapes.next) {
  71829. var parentShape = this._getLastShape(impostor.physicsBody);
  71830. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  71831. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  71832. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  71833. }
  71834. else {
  71835. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  71836. }
  71837. if (impostor.object.rotationQuaternion) {
  71838. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  71839. impostor.object.rotationQuaternion.normalize();
  71840. }
  71841. }
  71842. };
  71843. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71844. var body = impostor.physicsBody;
  71845. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  71846. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  71847. body.syncShapes();
  71848. body.awake();
  71849. };
  71850. OimoJSPlugin.prototype._getLastShape = function (body) {
  71851. var lastShape = body.shapes;
  71852. while (lastShape.next) {
  71853. lastShape = lastShape.next;
  71854. }
  71855. return lastShape;
  71856. };
  71857. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71858. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  71859. };
  71860. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71861. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  71862. };
  71863. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71864. var v = impostor.physicsBody.linearVelocity;
  71865. if (!v) {
  71866. return null;
  71867. }
  71868. return new BABYLON.Vector3(v.x, v.y, v.z);
  71869. };
  71870. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71871. var v = impostor.physicsBody.angularVelocity;
  71872. if (!v) {
  71873. return null;
  71874. }
  71875. return new BABYLON.Vector3(v.x, v.y, v.z);
  71876. };
  71877. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71878. var staticBody = mass === 0;
  71879. //this will actually set the body's density and not its mass.
  71880. //But this is how oimo treats the mass variable.
  71881. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  71882. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  71883. };
  71884. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  71885. return impostor.physicsBody.shapes.density;
  71886. };
  71887. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  71888. return impostor.physicsBody.shapes.friction;
  71889. };
  71890. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71891. impostor.physicsBody.shapes.friction = friction;
  71892. };
  71893. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71894. return impostor.physicsBody.shapes.restitution;
  71895. };
  71896. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71897. impostor.physicsBody.shapes.restitution = restitution;
  71898. };
  71899. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  71900. impostor.physicsBody.sleep();
  71901. };
  71902. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  71903. impostor.physicsBody.awake();
  71904. };
  71905. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71906. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  71907. if (minDistance !== void 0) {
  71908. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  71909. }
  71910. };
  71911. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71912. //TODO separate rotational and transational motors.
  71913. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71914. if (motor) {
  71915. motor.setMotor(speed, maxForce);
  71916. }
  71917. };
  71918. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  71919. //TODO separate rotational and transational motors.
  71920. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71921. if (motor) {
  71922. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  71923. }
  71924. };
  71925. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71926. var body = impostor.physicsBody;
  71927. mesh.position.x = body.position.x;
  71928. mesh.position.y = body.position.y;
  71929. mesh.position.z = body.position.z;
  71930. if (mesh.rotationQuaternion) {
  71931. mesh.rotationQuaternion.x = body.orientation.x;
  71932. mesh.rotationQuaternion.y = body.orientation.y;
  71933. mesh.rotationQuaternion.z = body.orientation.z;
  71934. mesh.rotationQuaternion.w = body.orientation.s;
  71935. }
  71936. };
  71937. OimoJSPlugin.prototype.getRadius = function (impostor) {
  71938. return impostor.physicsBody.shapes.radius;
  71939. };
  71940. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71941. var shape = impostor.physicsBody.shapes;
  71942. result.x = shape.halfWidth * 2;
  71943. result.y = shape.halfHeight * 2;
  71944. result.z = shape.halfDepth * 2;
  71945. };
  71946. OimoJSPlugin.prototype.dispose = function () {
  71947. this.world.clear();
  71948. };
  71949. return OimoJSPlugin;
  71950. }());
  71951. BABYLON.OimoJSPlugin = OimoJSPlugin;
  71952. })(BABYLON || (BABYLON = {}));
  71953. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  71954. var BABYLON;
  71955. (function (BABYLON) {
  71956. /*
  71957. * Based on jsTGALoader - Javascript loader for TGA file
  71958. * By Vincent Thibault
  71959. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  71960. */
  71961. var TGATools = /** @class */ (function () {
  71962. function TGATools() {
  71963. }
  71964. TGATools.GetTGAHeader = function (data) {
  71965. var offset = 0;
  71966. var header = {
  71967. id_length: data[offset++],
  71968. colormap_type: data[offset++],
  71969. image_type: data[offset++],
  71970. colormap_index: data[offset++] | data[offset++] << 8,
  71971. colormap_length: data[offset++] | data[offset++] << 8,
  71972. colormap_size: data[offset++],
  71973. origin: [
  71974. data[offset++] | data[offset++] << 8,
  71975. data[offset++] | data[offset++] << 8
  71976. ],
  71977. width: data[offset++] | data[offset++] << 8,
  71978. height: data[offset++] | data[offset++] << 8,
  71979. pixel_size: data[offset++],
  71980. flags: data[offset++]
  71981. };
  71982. return header;
  71983. };
  71984. TGATools.UploadContent = function (gl, data) {
  71985. // Not enough data to contain header ?
  71986. if (data.length < 19) {
  71987. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  71988. return;
  71989. }
  71990. // Read Header
  71991. var offset = 18;
  71992. var header = TGATools.GetTGAHeader(data);
  71993. // Assume it's a valid Targa file.
  71994. if (header.id_length + offset > data.length) {
  71995. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  71996. return;
  71997. }
  71998. // Skip not needed data
  71999. offset += header.id_length;
  72000. var use_rle = false;
  72001. var use_pal = false;
  72002. var use_grey = false;
  72003. // Get some informations.
  72004. switch (header.image_type) {
  72005. case TGATools._TYPE_RLE_INDEXED:
  72006. use_rle = true;
  72007. case TGATools._TYPE_INDEXED:
  72008. use_pal = true;
  72009. break;
  72010. case TGATools._TYPE_RLE_RGB:
  72011. use_rle = true;
  72012. case TGATools._TYPE_RGB:
  72013. // use_rgb = true;
  72014. break;
  72015. case TGATools._TYPE_RLE_GREY:
  72016. use_rle = true;
  72017. case TGATools._TYPE_GREY:
  72018. use_grey = true;
  72019. break;
  72020. }
  72021. var pixel_data;
  72022. // var numAlphaBits = header.flags & 0xf;
  72023. var pixel_size = header.pixel_size >> 3;
  72024. var pixel_total = header.width * header.height * pixel_size;
  72025. // Read palettes
  72026. var palettes;
  72027. if (use_pal) {
  72028. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  72029. }
  72030. // Read LRE
  72031. if (use_rle) {
  72032. pixel_data = new Uint8Array(pixel_total);
  72033. var c, count, i;
  72034. var localOffset = 0;
  72035. var pixels = new Uint8Array(pixel_size);
  72036. while (offset < pixel_total && localOffset < pixel_total) {
  72037. c = data[offset++];
  72038. count = (c & 0x7f) + 1;
  72039. // RLE pixels
  72040. if (c & 0x80) {
  72041. // Bind pixel tmp array
  72042. for (i = 0; i < pixel_size; ++i) {
  72043. pixels[i] = data[offset++];
  72044. }
  72045. // Copy pixel array
  72046. for (i = 0; i < count; ++i) {
  72047. pixel_data.set(pixels, localOffset + i * pixel_size);
  72048. }
  72049. localOffset += pixel_size * count;
  72050. }
  72051. else {
  72052. count *= pixel_size;
  72053. for (i = 0; i < count; ++i) {
  72054. pixel_data[localOffset + i] = data[offset++];
  72055. }
  72056. localOffset += count;
  72057. }
  72058. }
  72059. }
  72060. else {
  72061. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  72062. }
  72063. // Load to texture
  72064. var x_start, y_start, x_step, y_step, y_end, x_end;
  72065. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  72066. default:
  72067. case TGATools._ORIGIN_UL:
  72068. x_start = 0;
  72069. x_step = 1;
  72070. x_end = header.width;
  72071. y_start = 0;
  72072. y_step = 1;
  72073. y_end = header.height;
  72074. break;
  72075. case TGATools._ORIGIN_BL:
  72076. x_start = 0;
  72077. x_step = 1;
  72078. x_end = header.width;
  72079. y_start = header.height - 1;
  72080. y_step = -1;
  72081. y_end = -1;
  72082. break;
  72083. case TGATools._ORIGIN_UR:
  72084. x_start = header.width - 1;
  72085. x_step = -1;
  72086. x_end = -1;
  72087. y_start = 0;
  72088. y_step = 1;
  72089. y_end = header.height;
  72090. break;
  72091. case TGATools._ORIGIN_BR:
  72092. x_start = header.width - 1;
  72093. x_step = -1;
  72094. x_end = -1;
  72095. y_start = header.height - 1;
  72096. y_step = -1;
  72097. y_end = -1;
  72098. break;
  72099. }
  72100. // Load the specify method
  72101. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  72102. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  72103. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  72104. };
  72105. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72106. var image = pixel_data, colormap = palettes;
  72107. var width = header.width, height = header.height;
  72108. var color, i = 0, x, y;
  72109. var imageData = new Uint8Array(width * height * 4);
  72110. for (y = y_start; y !== y_end; y += y_step) {
  72111. for (x = x_start; x !== x_end; x += x_step, i++) {
  72112. color = image[i];
  72113. imageData[(x + width * y) * 4 + 3] = 255;
  72114. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  72115. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  72116. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  72117. }
  72118. }
  72119. return imageData;
  72120. };
  72121. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72122. var image = pixel_data;
  72123. var width = header.width, height = header.height;
  72124. var color, i = 0, x, y;
  72125. var imageData = new Uint8Array(width * height * 4);
  72126. for (y = y_start; y !== y_end; y += y_step) {
  72127. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72128. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  72129. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  72130. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  72131. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  72132. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  72133. }
  72134. }
  72135. return imageData;
  72136. };
  72137. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72138. var image = pixel_data;
  72139. var width = header.width, height = header.height;
  72140. var i = 0, x, y;
  72141. var imageData = new Uint8Array(width * height * 4);
  72142. for (y = y_start; y !== y_end; y += y_step) {
  72143. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  72144. imageData[(x + width * y) * 4 + 3] = 255;
  72145. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72146. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72147. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72148. }
  72149. }
  72150. return imageData;
  72151. };
  72152. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72153. var image = pixel_data;
  72154. var width = header.width, height = header.height;
  72155. var i = 0, x, y;
  72156. var imageData = new Uint8Array(width * height * 4);
  72157. for (y = y_start; y !== y_end; y += y_step) {
  72158. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  72159. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72160. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72161. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72162. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  72163. }
  72164. }
  72165. return imageData;
  72166. };
  72167. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72168. var image = pixel_data;
  72169. var width = header.width, height = header.height;
  72170. var color, i = 0, x, y;
  72171. var imageData = new Uint8Array(width * height * 4);
  72172. for (y = y_start; y !== y_end; y += y_step) {
  72173. for (x = x_start; x !== x_end; x += x_step, i++) {
  72174. color = image[i];
  72175. imageData[(x + width * y) * 4 + 0] = color;
  72176. imageData[(x + width * y) * 4 + 1] = color;
  72177. imageData[(x + width * y) * 4 + 2] = color;
  72178. imageData[(x + width * y) * 4 + 3] = 255;
  72179. }
  72180. }
  72181. return imageData;
  72182. };
  72183. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72184. var image = pixel_data;
  72185. var width = header.width, height = header.height;
  72186. var i = 0, x, y;
  72187. var imageData = new Uint8Array(width * height * 4);
  72188. for (y = y_start; y !== y_end; y += y_step) {
  72189. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72190. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72191. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72192. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72193. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72194. }
  72195. }
  72196. return imageData;
  72197. };
  72198. //private static _TYPE_NO_DATA = 0;
  72199. TGATools._TYPE_INDEXED = 1;
  72200. TGATools._TYPE_RGB = 2;
  72201. TGATools._TYPE_GREY = 3;
  72202. TGATools._TYPE_RLE_INDEXED = 9;
  72203. TGATools._TYPE_RLE_RGB = 10;
  72204. TGATools._TYPE_RLE_GREY = 11;
  72205. TGATools._ORIGIN_MASK = 0x30;
  72206. TGATools._ORIGIN_SHIFT = 0x04;
  72207. TGATools._ORIGIN_BL = 0x00;
  72208. TGATools._ORIGIN_BR = 0x01;
  72209. TGATools._ORIGIN_UL = 0x02;
  72210. TGATools._ORIGIN_UR = 0x03;
  72211. return TGATools;
  72212. }());
  72213. BABYLON.TGATools = TGATools;
  72214. })(BABYLON || (BABYLON = {}));
  72215. //# sourceMappingURL=babylon.tga.js.map
  72216. var BABYLON;
  72217. (function (BABYLON) {
  72218. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72219. // All values and structures referenced from:
  72220. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72221. var DDS_MAGIC = 0x20534444;
  72222. var
  72223. //DDSD_CAPS = 0x1,
  72224. //DDSD_HEIGHT = 0x2,
  72225. //DDSD_WIDTH = 0x4,
  72226. //DDSD_PITCH = 0x8,
  72227. //DDSD_PIXELFORMAT = 0x1000,
  72228. DDSD_MIPMAPCOUNT = 0x20000;
  72229. //DDSD_LINEARSIZE = 0x80000,
  72230. //DDSD_DEPTH = 0x800000;
  72231. // var DDSCAPS_COMPLEX = 0x8,
  72232. // DDSCAPS_MIPMAP = 0x400000,
  72233. // DDSCAPS_TEXTURE = 0x1000;
  72234. var DDSCAPS2_CUBEMAP = 0x200;
  72235. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72236. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72237. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72238. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72239. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72240. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72241. // DDSCAPS2_VOLUME = 0x200000;
  72242. var
  72243. //DDPF_ALPHAPIXELS = 0x1,
  72244. //DDPF_ALPHA = 0x2,
  72245. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72246. //DDPF_YUV = 0x200,
  72247. DDPF_LUMINANCE = 0x20000;
  72248. function FourCCToInt32(value) {
  72249. return value.charCodeAt(0) +
  72250. (value.charCodeAt(1) << 8) +
  72251. (value.charCodeAt(2) << 16) +
  72252. (value.charCodeAt(3) << 24);
  72253. }
  72254. function Int32ToFourCC(value) {
  72255. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72256. }
  72257. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72258. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72259. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72260. var FOURCC_DX10 = FourCCToInt32("DX10");
  72261. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72262. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72263. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72264. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72265. var headerLengthInt = 31; // The header length in 32 bit ints
  72266. // Offsets into the header array
  72267. var off_magic = 0;
  72268. var off_size = 1;
  72269. var off_flags = 2;
  72270. var off_height = 3;
  72271. var off_width = 4;
  72272. var off_mipmapCount = 7;
  72273. var off_pfFlags = 20;
  72274. var off_pfFourCC = 21;
  72275. var off_RGBbpp = 22;
  72276. var off_RMask = 23;
  72277. var off_GMask = 24;
  72278. var off_BMask = 25;
  72279. var off_AMask = 26;
  72280. // var off_caps1 = 27;
  72281. var off_caps2 = 28;
  72282. // var off_caps3 = 29;
  72283. // var off_caps4 = 30;
  72284. var off_dxgiFormat = 32;
  72285. ;
  72286. var DDSTools = /** @class */ (function () {
  72287. function DDSTools() {
  72288. }
  72289. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72290. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72291. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72292. var mipmapCount = 1;
  72293. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72294. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72295. }
  72296. var fourCC = header[off_pfFourCC];
  72297. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72298. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72299. switch (fourCC) {
  72300. case FOURCC_D3DFMT_R16G16B16A16F:
  72301. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72302. break;
  72303. case FOURCC_D3DFMT_R32G32B32A32F:
  72304. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72305. break;
  72306. case FOURCC_DX10:
  72307. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72308. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72309. break;
  72310. }
  72311. }
  72312. return {
  72313. width: header[off_width],
  72314. height: header[off_height],
  72315. mipmapCount: mipmapCount,
  72316. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72317. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72318. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72319. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72320. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72321. dxgiFormat: dxgiFormat,
  72322. textureType: textureType
  72323. };
  72324. };
  72325. DDSTools._ToHalfFloat = function (value) {
  72326. if (!DDSTools._FloatView) {
  72327. DDSTools._FloatView = new Float32Array(1);
  72328. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72329. }
  72330. DDSTools._FloatView[0] = value;
  72331. var x = DDSTools._Int32View[0];
  72332. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72333. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72334. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72335. /* If zero, or denormal, or exponent underflows too much for a denormal
  72336. * half, return signed zero. */
  72337. if (e < 103) {
  72338. return bits;
  72339. }
  72340. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72341. if (e > 142) {
  72342. bits |= 0x7c00;
  72343. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72344. * not Inf, so make sure we set one mantissa bit too. */
  72345. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72346. return bits;
  72347. }
  72348. /* If exponent underflows but not too much, return a denormal */
  72349. if (e < 113) {
  72350. m |= 0x0800;
  72351. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72352. * to 1, which is OK. */
  72353. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72354. return bits;
  72355. }
  72356. bits |= ((e - 112) << 10) | (m >> 1);
  72357. bits += m & 1;
  72358. return bits;
  72359. };
  72360. DDSTools._FromHalfFloat = function (value) {
  72361. var s = (value & 0x8000) >> 15;
  72362. var e = (value & 0x7C00) >> 10;
  72363. var f = value & 0x03FF;
  72364. if (e === 0) {
  72365. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72366. }
  72367. else if (e == 0x1F) {
  72368. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72369. }
  72370. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72371. };
  72372. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72373. var destArray = new Float32Array(dataLength);
  72374. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72375. var index = 0;
  72376. for (var y = 0; y < height; y++) {
  72377. for (var x = 0; x < width; x++) {
  72378. var srcPos = (x + y * width) * 4;
  72379. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72380. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72381. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72382. if (DDSTools.StoreLODInAlphaChannel) {
  72383. destArray[index + 3] = lod;
  72384. }
  72385. else {
  72386. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72387. }
  72388. index += 4;
  72389. }
  72390. }
  72391. return destArray;
  72392. };
  72393. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72394. if (DDSTools.StoreLODInAlphaChannel) {
  72395. var destArray = new Uint16Array(dataLength);
  72396. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72397. var index = 0;
  72398. for (var y = 0; y < height; y++) {
  72399. for (var x = 0; x < width; x++) {
  72400. var srcPos = (x + y * width) * 4;
  72401. destArray[index] = srcData[srcPos];
  72402. destArray[index + 1] = srcData[srcPos + 1];
  72403. destArray[index + 2] = srcData[srcPos + 2];
  72404. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72405. index += 4;
  72406. }
  72407. }
  72408. return destArray;
  72409. }
  72410. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  72411. };
  72412. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72413. if (DDSTools.StoreLODInAlphaChannel) {
  72414. var destArray = new Float32Array(dataLength);
  72415. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72416. var index = 0;
  72417. for (var y = 0; y < height; y++) {
  72418. for (var x = 0; x < width; x++) {
  72419. var srcPos = (x + y * width) * 4;
  72420. destArray[index] = srcData[srcPos];
  72421. destArray[index + 1] = srcData[srcPos + 1];
  72422. destArray[index + 2] = srcData[srcPos + 2];
  72423. destArray[index + 3] = lod;
  72424. index += 4;
  72425. }
  72426. }
  72427. return destArray;
  72428. }
  72429. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  72430. };
  72431. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72432. var destArray = new Uint8Array(dataLength);
  72433. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72434. var index = 0;
  72435. for (var y = 0; y < height; y++) {
  72436. for (var x = 0; x < width; x++) {
  72437. var srcPos = (x + y * width) * 4;
  72438. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  72439. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  72440. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  72441. if (DDSTools.StoreLODInAlphaChannel) {
  72442. destArray[index + 3] = lod;
  72443. }
  72444. else {
  72445. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  72446. }
  72447. index += 4;
  72448. }
  72449. }
  72450. return destArray;
  72451. };
  72452. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72453. var destArray = new Uint8Array(dataLength);
  72454. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72455. var index = 0;
  72456. for (var y = 0; y < height; y++) {
  72457. for (var x = 0; x < width; x++) {
  72458. var srcPos = (x + y * width) * 4;
  72459. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  72460. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  72461. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  72462. if (DDSTools.StoreLODInAlphaChannel) {
  72463. destArray[index + 3] = lod;
  72464. }
  72465. else {
  72466. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  72467. }
  72468. index += 4;
  72469. }
  72470. }
  72471. return destArray;
  72472. };
  72473. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  72474. var byteArray = new Uint8Array(dataLength);
  72475. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72476. var index = 0;
  72477. for (var y = 0; y < height; y++) {
  72478. for (var x = 0; x < width; x++) {
  72479. var srcPos = (x + y * width) * 4;
  72480. byteArray[index] = srcData[srcPos + rOffset];
  72481. byteArray[index + 1] = srcData[srcPos + gOffset];
  72482. byteArray[index + 2] = srcData[srcPos + bOffset];
  72483. byteArray[index + 3] = srcData[srcPos + aOffset];
  72484. index += 4;
  72485. }
  72486. }
  72487. return byteArray;
  72488. };
  72489. DDSTools._ExtractLongWordOrder = function (value) {
  72490. if (value === 0 || value === 255 || value === -16777216) {
  72491. return 0;
  72492. }
  72493. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  72494. };
  72495. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  72496. var byteArray = new Uint8Array(dataLength);
  72497. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72498. var index = 0;
  72499. for (var y = 0; y < height; y++) {
  72500. for (var x = 0; x < width; x++) {
  72501. var srcPos = (x + y * width) * 3;
  72502. byteArray[index] = srcData[srcPos + rOffset];
  72503. byteArray[index + 1] = srcData[srcPos + gOffset];
  72504. byteArray[index + 2] = srcData[srcPos + bOffset];
  72505. index += 3;
  72506. }
  72507. }
  72508. return byteArray;
  72509. };
  72510. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  72511. var byteArray = new Uint8Array(dataLength);
  72512. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72513. var index = 0;
  72514. for (var y = 0; y < height; y++) {
  72515. for (var x = 0; x < width; x++) {
  72516. var srcPos = (x + y * width);
  72517. byteArray[index] = srcData[srcPos];
  72518. index++;
  72519. }
  72520. }
  72521. return byteArray;
  72522. };
  72523. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  72524. if (lodIndex === void 0) { lodIndex = -1; }
  72525. var ext = engine.getCaps().s3tc;
  72526. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72527. var fourCC, width, height, dataLength = 0, dataOffset;
  72528. var byteArray, mipmapCount, mip;
  72529. var internalFormat = 0;
  72530. var format = 0;
  72531. var blockBytes = 1;
  72532. if (header[off_magic] !== DDS_MAGIC) {
  72533. BABYLON.Tools.Error("Invalid magic number in DDS header");
  72534. return;
  72535. }
  72536. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  72537. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  72538. return;
  72539. }
  72540. if (info.isCompressed && !ext) {
  72541. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  72542. return;
  72543. }
  72544. var bpp = header[off_RGBbpp];
  72545. dataOffset = header[off_size] + 4;
  72546. var computeFormats = false;
  72547. if (info.isFourCC) {
  72548. fourCC = header[off_pfFourCC];
  72549. switch (fourCC) {
  72550. case FOURCC_DXT1:
  72551. blockBytes = 8;
  72552. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  72553. break;
  72554. case FOURCC_DXT3:
  72555. blockBytes = 16;
  72556. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  72557. break;
  72558. case FOURCC_DXT5:
  72559. blockBytes = 16;
  72560. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  72561. break;
  72562. case FOURCC_D3DFMT_R16G16B16A16F:
  72563. computeFormats = true;
  72564. break;
  72565. case FOURCC_D3DFMT_R32G32B32A32F:
  72566. computeFormats = true;
  72567. break;
  72568. case FOURCC_DX10:
  72569. // There is an additionnal header so dataOffset need to be changed
  72570. dataOffset += 5 * 4; // 5 uints
  72571. var supported = false;
  72572. switch (info.dxgiFormat) {
  72573. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  72574. computeFormats = true;
  72575. supported = true;
  72576. break;
  72577. case DXGI_FORMAT_B8G8R8X8_UNORM:
  72578. info.isRGB = true;
  72579. info.isFourCC = false;
  72580. bpp = 32;
  72581. supported = true;
  72582. break;
  72583. }
  72584. if (supported) {
  72585. break;
  72586. }
  72587. default:
  72588. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  72589. return;
  72590. }
  72591. }
  72592. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  72593. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  72594. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  72595. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  72596. if (computeFormats) {
  72597. format = engine._getWebGLTextureType(info.textureType);
  72598. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72599. }
  72600. mipmapCount = 1;
  72601. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  72602. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72603. }
  72604. for (var face = 0; face < faces; face++) {
  72605. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  72606. width = header[off_width];
  72607. height = header[off_height];
  72608. for (mip = 0; mip < mipmapCount; ++mip) {
  72609. if (lodIndex === -1 || lodIndex === mip) {
  72610. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  72611. var i = (lodIndex === -1) ? mip : 0;
  72612. if (!info.isCompressed && info.isFourCC) {
  72613. dataLength = width * height * 4;
  72614. var floatArray = null;
  72615. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  72616. if (bpp === 128) {
  72617. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72618. }
  72619. else if (bpp === 64) {
  72620. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72621. }
  72622. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72623. format = engine._getWebGLTextureType(info.textureType);
  72624. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72625. }
  72626. else {
  72627. if (bpp === 128) {
  72628. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72629. }
  72630. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  72631. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72632. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72633. format = engine._getWebGLTextureType(info.textureType);
  72634. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72635. }
  72636. else {
  72637. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72638. }
  72639. }
  72640. if (floatArray) {
  72641. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  72642. }
  72643. }
  72644. else if (info.isRGB) {
  72645. if (bpp === 24) {
  72646. dataLength = width * height * 3;
  72647. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  72648. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  72649. }
  72650. else {
  72651. dataLength = width * height * 4;
  72652. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  72653. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  72654. }
  72655. }
  72656. else if (info.isLuminance) {
  72657. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  72658. var unpaddedRowSize = width;
  72659. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  72660. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  72661. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  72662. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  72663. }
  72664. else {
  72665. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  72666. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  72667. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  72668. }
  72669. }
  72670. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  72671. width *= 0.5;
  72672. height *= 0.5;
  72673. width = Math.max(1.0, width);
  72674. height = Math.max(1.0, height);
  72675. }
  72676. if (currentFace !== undefined) {
  72677. // Loading a single face
  72678. break;
  72679. }
  72680. }
  72681. };
  72682. DDSTools.StoreLODInAlphaChannel = false;
  72683. return DDSTools;
  72684. }());
  72685. BABYLON.DDSTools = DDSTools;
  72686. })(BABYLON || (BABYLON = {}));
  72687. //# sourceMappingURL=babylon.dds.js.map
  72688. var BABYLON;
  72689. (function (BABYLON) {
  72690. /**
  72691. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  72692. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  72693. */
  72694. var KhronosTextureContainer = /** @class */ (function () {
  72695. /**
  72696. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  72697. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  72698. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  72699. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  72700. */
  72701. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  72702. this.arrayBuffer = arrayBuffer;
  72703. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  72704. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  72705. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  72706. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  72707. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  72708. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  72709. BABYLON.Tools.Error("texture missing KTX identifier");
  72710. return;
  72711. }
  72712. // load the reset of the header in native 32 bit int
  72713. var header = new Int32Array(this.arrayBuffer, 12, 13);
  72714. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  72715. var oppositeEndianess = header[0] === 0x01020304;
  72716. // read all the header elements in order they exist in the file, without modification (sans endainness)
  72717. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  72718. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  72719. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  72720. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  72721. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  72722. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  72723. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  72724. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  72725. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  72726. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  72727. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  72728. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  72729. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  72730. if (this.glType !== 0) {
  72731. BABYLON.Tools.Error("only compressed formats currently supported");
  72732. return;
  72733. }
  72734. else {
  72735. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  72736. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  72737. }
  72738. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  72739. BABYLON.Tools.Error("only 2D textures currently supported");
  72740. return;
  72741. }
  72742. if (this.numberOfArrayElements !== 0) {
  72743. BABYLON.Tools.Error("texture arrays not currently supported");
  72744. return;
  72745. }
  72746. if (this.numberOfFaces !== facesExpected) {
  72747. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  72748. return;
  72749. }
  72750. // we now have a completely validated file, so could use existence of loadType as success
  72751. // would need to make this more elaborate & adjust checks above to support more than one load type
  72752. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  72753. }
  72754. // not as fast hardware based, but will probably never need to use
  72755. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  72756. return ((val & 0xFF) << 24)
  72757. | ((val & 0xFF00) << 8)
  72758. | ((val >> 8) & 0xFF00)
  72759. | ((val >> 24) & 0xFF);
  72760. };
  72761. /**
  72762. * It is assumed that the texture has already been created & is currently bound
  72763. */
  72764. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  72765. switch (this.loadType) {
  72766. case KhronosTextureContainer.COMPRESSED_2D:
  72767. this._upload2DCompressedLevels(gl, loadMipmaps);
  72768. break;
  72769. case KhronosTextureContainer.TEX_2D:
  72770. case KhronosTextureContainer.COMPRESSED_3D:
  72771. case KhronosTextureContainer.TEX_3D:
  72772. }
  72773. };
  72774. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  72775. // initialize width & height for level 1
  72776. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  72777. var width = this.pixelWidth;
  72778. var height = this.pixelHeight;
  72779. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  72780. for (var level = 0; level < mipmapCount; level++) {
  72781. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  72782. for (var face = 0; face < this.numberOfFaces; face++) {
  72783. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  72784. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  72785. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  72786. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  72787. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  72788. }
  72789. width = Math.max(1.0, width * 0.5);
  72790. height = Math.max(1.0, height * 0.5);
  72791. }
  72792. };
  72793. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  72794. // load types
  72795. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  72796. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  72797. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  72798. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  72799. return KhronosTextureContainer;
  72800. }());
  72801. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  72802. })(BABYLON || (BABYLON = {}));
  72803. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  72804. var BABYLON;
  72805. (function (BABYLON) {
  72806. var Debug = /** @class */ (function () {
  72807. function Debug() {
  72808. }
  72809. Debug.AxesViewer = /** @class */ (function () {
  72810. function AxesViewer(scene, scaleLines) {
  72811. if (scaleLines === void 0) { scaleLines = 1; }
  72812. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72813. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72814. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72815. this.scaleLines = 1;
  72816. this.scaleLines = scaleLines;
  72817. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  72818. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  72819. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  72820. this._xmesh.renderingGroupId = 2;
  72821. this._ymesh.renderingGroupId = 2;
  72822. this._zmesh.renderingGroupId = 2;
  72823. this._xmesh.material.checkReadyOnlyOnce = true;
  72824. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  72825. this._ymesh.material.checkReadyOnlyOnce = true;
  72826. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  72827. this._zmesh.material.checkReadyOnlyOnce = true;
  72828. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  72829. this.scene = scene;
  72830. }
  72831. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  72832. var scaleLines = this.scaleLines;
  72833. if (this._xmesh) {
  72834. this._xmesh.position.copyFrom(position);
  72835. }
  72836. if (this._ymesh) {
  72837. this._ymesh.position.copyFrom(position);
  72838. }
  72839. if (this._zmesh) {
  72840. this._zmesh.position.copyFrom(position);
  72841. }
  72842. var point2 = this._xline[1];
  72843. point2.x = xaxis.x * scaleLines;
  72844. point2.y = xaxis.y * scaleLines;
  72845. point2.z = xaxis.z * scaleLines;
  72846. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  72847. point2 = this._yline[1];
  72848. point2.x = yaxis.x * scaleLines;
  72849. point2.y = yaxis.y * scaleLines;
  72850. point2.z = yaxis.z * scaleLines;
  72851. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  72852. point2 = this._zline[1];
  72853. point2.x = zaxis.x * scaleLines;
  72854. point2.y = zaxis.y * scaleLines;
  72855. point2.z = zaxis.z * scaleLines;
  72856. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  72857. };
  72858. AxesViewer.prototype.dispose = function () {
  72859. if (this._xmesh) {
  72860. this._xmesh.dispose();
  72861. }
  72862. if (this._ymesh) {
  72863. this._ymesh.dispose();
  72864. }
  72865. if (this._zmesh) {
  72866. this._zmesh.dispose();
  72867. }
  72868. this._xmesh = null;
  72869. this._ymesh = null;
  72870. this._zmesh = null;
  72871. this.scene = null;
  72872. };
  72873. return AxesViewer;
  72874. }());
  72875. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  72876. __extends(BoneAxesViewer, _super);
  72877. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  72878. if (scaleLines === void 0) { scaleLines = 1; }
  72879. var _this = _super.call(this, scene, scaleLines) || this;
  72880. _this.pos = BABYLON.Vector3.Zero();
  72881. _this.xaxis = BABYLON.Vector3.Zero();
  72882. _this.yaxis = BABYLON.Vector3.Zero();
  72883. _this.zaxis = BABYLON.Vector3.Zero();
  72884. _this.mesh = mesh;
  72885. _this.bone = bone;
  72886. return _this;
  72887. }
  72888. BoneAxesViewer.prototype.update = function () {
  72889. if (!this.mesh || !this.bone) {
  72890. return;
  72891. }
  72892. var bone = this.bone;
  72893. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  72894. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  72895. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  72896. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  72897. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  72898. };
  72899. BoneAxesViewer.prototype.dispose = function () {
  72900. if (this.mesh) {
  72901. this.mesh = null;
  72902. this.bone = null;
  72903. _super.prototype.dispose.call(this);
  72904. }
  72905. };
  72906. return BoneAxesViewer;
  72907. }(Debug.AxesViewer));
  72908. Debug.PhysicsViewer = /** @class */ (function () {
  72909. function PhysicsViewer(scene) {
  72910. this._impostors = [];
  72911. this._meshes = [];
  72912. this._numMeshes = 0;
  72913. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72914. var physicEngine = this._scene.getPhysicsEngine();
  72915. if (physicEngine) {
  72916. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  72917. }
  72918. }
  72919. PhysicsViewer.prototype._updateDebugMeshes = function () {
  72920. var plugin = this._physicsEnginePlugin;
  72921. for (var i = 0; i < this._numMeshes; i++) {
  72922. var impostor = this._impostors[i];
  72923. if (!impostor) {
  72924. continue;
  72925. }
  72926. if (impostor.isDisposed) {
  72927. this.hideImpostor(this._impostors[i--]);
  72928. }
  72929. else {
  72930. var mesh = this._meshes[i];
  72931. if (mesh && plugin) {
  72932. plugin.syncMeshWithImpostor(mesh, impostor);
  72933. }
  72934. }
  72935. }
  72936. };
  72937. PhysicsViewer.prototype.showImpostor = function (impostor) {
  72938. if (!this._scene) {
  72939. return;
  72940. }
  72941. for (var i = 0; i < this._numMeshes; i++) {
  72942. if (this._impostors[i] == impostor) {
  72943. return;
  72944. }
  72945. }
  72946. var debugMesh = this._getDebugMesh(impostor, this._scene);
  72947. if (debugMesh) {
  72948. this._impostors[this._numMeshes] = impostor;
  72949. this._meshes[this._numMeshes] = debugMesh;
  72950. if (this._numMeshes === 0) {
  72951. this._renderFunction = this._updateDebugMeshes.bind(this);
  72952. this._scene.registerBeforeRender(this._renderFunction);
  72953. }
  72954. this._numMeshes++;
  72955. }
  72956. };
  72957. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  72958. if (!impostor || !this._scene) {
  72959. return;
  72960. }
  72961. var removed = false;
  72962. for (var i = 0; i < this._numMeshes; i++) {
  72963. if (this._impostors[i] == impostor) {
  72964. var mesh = this._meshes[i];
  72965. if (!mesh) {
  72966. continue;
  72967. }
  72968. this._scene.removeMesh(mesh);
  72969. mesh.dispose();
  72970. this._numMeshes--;
  72971. if (this._numMeshes > 0) {
  72972. this._meshes[i] = this._meshes[this._numMeshes];
  72973. this._impostors[i] = this._impostors[this._numMeshes];
  72974. this._meshes[this._numMeshes] = null;
  72975. this._impostors[this._numMeshes] = null;
  72976. }
  72977. else {
  72978. this._meshes[0] = null;
  72979. this._impostors[0] = null;
  72980. }
  72981. removed = true;
  72982. break;
  72983. }
  72984. }
  72985. if (removed && this._numMeshes === 0) {
  72986. this._scene.unregisterBeforeRender(this._renderFunction);
  72987. }
  72988. };
  72989. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  72990. if (!this._debugMaterial) {
  72991. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  72992. this._debugMaterial.wireframe = true;
  72993. }
  72994. return this._debugMaterial;
  72995. };
  72996. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  72997. if (!this._debugBoxMesh) {
  72998. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  72999. this._debugBoxMesh.renderingGroupId = 1;
  73000. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73001. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  73002. scene.removeMesh(this._debugBoxMesh);
  73003. }
  73004. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  73005. };
  73006. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  73007. if (!this._debugSphereMesh) {
  73008. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  73009. this._debugSphereMesh.renderingGroupId = 1;
  73010. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73011. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  73012. scene.removeMesh(this._debugSphereMesh);
  73013. }
  73014. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  73015. };
  73016. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  73017. var mesh = null;
  73018. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  73019. mesh = this._getDebugBoxMesh(scene);
  73020. impostor.getBoxSizeToRef(mesh.scaling);
  73021. }
  73022. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  73023. mesh = this._getDebugSphereMesh(scene);
  73024. var radius = impostor.getRadius();
  73025. mesh.scaling.x = radius * 2;
  73026. mesh.scaling.y = radius * 2;
  73027. mesh.scaling.z = radius * 2;
  73028. }
  73029. return mesh;
  73030. };
  73031. PhysicsViewer.prototype.dispose = function () {
  73032. for (var i = 0; i < this._numMeshes; i++) {
  73033. this.hideImpostor(this._impostors[i]);
  73034. }
  73035. if (this._debugBoxMesh) {
  73036. this._debugBoxMesh.dispose();
  73037. }
  73038. if (this._debugSphereMesh) {
  73039. this._debugSphereMesh.dispose();
  73040. }
  73041. if (this._debugMaterial) {
  73042. this._debugMaterial.dispose();
  73043. }
  73044. this._impostors.length = 0;
  73045. this._scene = null;
  73046. this._physicsEnginePlugin = null;
  73047. };
  73048. return PhysicsViewer;
  73049. }());
  73050. Debug.SkeletonViewer = /** @class */ (function () {
  73051. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  73052. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  73053. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  73054. this.skeleton = skeleton;
  73055. this.mesh = mesh;
  73056. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  73057. this.renderingGroupId = renderingGroupId;
  73058. this.color = BABYLON.Color3.White();
  73059. this._debugLines = new Array();
  73060. this._isEnabled = false;
  73061. this._scene = scene;
  73062. this.update();
  73063. this._renderFunction = this.update.bind(this);
  73064. }
  73065. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  73066. get: function () {
  73067. return this._isEnabled;
  73068. },
  73069. set: function (value) {
  73070. if (this._isEnabled === value) {
  73071. return;
  73072. }
  73073. this._isEnabled = value;
  73074. if (value) {
  73075. this._scene.registerBeforeRender(this._renderFunction);
  73076. }
  73077. else {
  73078. this._scene.unregisterBeforeRender(this._renderFunction);
  73079. }
  73080. },
  73081. enumerable: true,
  73082. configurable: true
  73083. });
  73084. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  73085. if (x === void 0) { x = 0; }
  73086. if (y === void 0) { y = 0; }
  73087. if (z === void 0) { z = 0; }
  73088. var tmat = BABYLON.Tmp.Matrix[0];
  73089. var parentBone = bone.getParent();
  73090. tmat.copyFrom(bone.getLocalMatrix());
  73091. if (x !== 0 || y !== 0 || z !== 0) {
  73092. var tmat2 = BABYLON.Tmp.Matrix[1];
  73093. BABYLON.Matrix.IdentityToRef(tmat2);
  73094. tmat2.m[12] = x;
  73095. tmat2.m[13] = y;
  73096. tmat2.m[14] = z;
  73097. tmat2.multiplyToRef(tmat, tmat);
  73098. }
  73099. if (parentBone) {
  73100. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  73101. }
  73102. tmat.multiplyToRef(meshMat, tmat);
  73103. position.x = tmat.m[12];
  73104. position.y = tmat.m[13];
  73105. position.z = tmat.m[14];
  73106. };
  73107. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  73108. var len = bones.length;
  73109. var meshPos = this.mesh.position;
  73110. for (var i = 0; i < len; i++) {
  73111. var bone = bones[i];
  73112. var points = this._debugLines[i];
  73113. if (!points) {
  73114. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73115. this._debugLines[i] = points;
  73116. }
  73117. this._getBonePosition(points[0], bone, meshMat);
  73118. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  73119. points[0].subtractInPlace(meshPos);
  73120. points[1].subtractInPlace(meshPos);
  73121. }
  73122. };
  73123. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  73124. var len = bones.length;
  73125. var boneNum = 0;
  73126. var meshPos = this.mesh.position;
  73127. for (var i = len - 1; i >= 0; i--) {
  73128. var childBone = bones[i];
  73129. var parentBone = childBone.getParent();
  73130. if (!parentBone) {
  73131. continue;
  73132. }
  73133. var points = this._debugLines[boneNum];
  73134. if (!points) {
  73135. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73136. this._debugLines[boneNum] = points;
  73137. }
  73138. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  73139. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  73140. points[0].subtractInPlace(meshPos);
  73141. points[1].subtractInPlace(meshPos);
  73142. boneNum++;
  73143. }
  73144. };
  73145. SkeletonViewer.prototype.update = function () {
  73146. if (this.autoUpdateBonesMatrices) {
  73147. this.skeleton.computeAbsoluteTransforms();
  73148. }
  73149. if (this.skeleton.bones[0].length === undefined) {
  73150. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73151. }
  73152. else {
  73153. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73154. }
  73155. if (!this._debugMesh) {
  73156. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  73157. this._debugMesh.renderingGroupId = this.renderingGroupId;
  73158. }
  73159. else {
  73160. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  73161. }
  73162. this._debugMesh.position.copyFrom(this.mesh.position);
  73163. this._debugMesh.color = this.color;
  73164. };
  73165. SkeletonViewer.prototype.dispose = function () {
  73166. if (this._debugMesh) {
  73167. this.isEnabled = false;
  73168. this._debugMesh.dispose();
  73169. this._debugMesh = null;
  73170. }
  73171. };
  73172. return SkeletonViewer;
  73173. }());
  73174. return Debug;
  73175. }());
  73176. BABYLON.Debug = Debug;
  73177. })(BABYLON || (BABYLON = {}));
  73178. //# sourceMappingURL=babylon.debugModules.js.map
  73179. var BABYLON;
  73180. (function (BABYLON) {
  73181. var RayHelper = /** @class */ (function () {
  73182. function RayHelper(ray) {
  73183. this.ray = ray;
  73184. }
  73185. RayHelper.CreateAndShow = function (ray, scene, color) {
  73186. var helper = new RayHelper(ray);
  73187. helper.show(scene, color);
  73188. return helper;
  73189. };
  73190. RayHelper.prototype.show = function (scene, color) {
  73191. if (!this._renderFunction && this.ray) {
  73192. var ray = this.ray;
  73193. this._renderFunction = this._render.bind(this);
  73194. this._scene = scene;
  73195. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73196. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73197. if (this._renderFunction) {
  73198. this._scene.registerBeforeRender(this._renderFunction);
  73199. }
  73200. }
  73201. if (color && this._renderLine) {
  73202. this._renderLine.color.copyFrom(color);
  73203. }
  73204. };
  73205. RayHelper.prototype.hide = function () {
  73206. if (this._renderFunction && this._scene) {
  73207. this._scene.unregisterBeforeRender(this._renderFunction);
  73208. this._scene = null;
  73209. this._renderFunction = null;
  73210. if (this._renderLine) {
  73211. this._renderLine.dispose();
  73212. this._renderLine = null;
  73213. }
  73214. this._renderPoints = [];
  73215. }
  73216. };
  73217. RayHelper.prototype._render = function () {
  73218. var ray = this.ray;
  73219. if (!ray) {
  73220. return;
  73221. }
  73222. var point = this._renderPoints[1];
  73223. var len = Math.min(ray.length, 1000000);
  73224. point.copyFrom(ray.direction);
  73225. point.scaleInPlace(len);
  73226. point.addInPlace(ray.origin);
  73227. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73228. };
  73229. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73230. this._attachedToMesh = mesh;
  73231. var ray = this.ray;
  73232. if (!ray) {
  73233. return;
  73234. }
  73235. if (!ray.direction) {
  73236. ray.direction = BABYLON.Vector3.Zero();
  73237. }
  73238. if (!ray.origin) {
  73239. ray.origin = BABYLON.Vector3.Zero();
  73240. }
  73241. if (length) {
  73242. ray.length = length;
  73243. }
  73244. if (!meshSpaceOrigin) {
  73245. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73246. }
  73247. if (!meshSpaceDirection) {
  73248. // -1 so that this will work with Mesh.lookAt
  73249. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73250. }
  73251. if (!this._meshSpaceDirection) {
  73252. this._meshSpaceDirection = meshSpaceDirection.clone();
  73253. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73254. }
  73255. else {
  73256. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73257. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73258. }
  73259. if (!this._updateToMeshFunction) {
  73260. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73261. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73262. }
  73263. this._updateToMesh();
  73264. };
  73265. RayHelper.prototype.detachFromMesh = function () {
  73266. if (this._attachedToMesh) {
  73267. if (this._updateToMeshFunction) {
  73268. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73269. }
  73270. this._attachedToMesh = null;
  73271. this._updateToMeshFunction = null;
  73272. }
  73273. };
  73274. RayHelper.prototype._updateToMesh = function () {
  73275. var ray = this.ray;
  73276. if (!this._attachedToMesh || !ray) {
  73277. return;
  73278. }
  73279. if (this._attachedToMesh._isDisposed) {
  73280. this.detachFromMesh();
  73281. return;
  73282. }
  73283. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73284. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73285. };
  73286. RayHelper.prototype.dispose = function () {
  73287. this.hide();
  73288. this.detachFromMesh();
  73289. this.ray = null;
  73290. };
  73291. return RayHelper;
  73292. }());
  73293. BABYLON.RayHelper = RayHelper;
  73294. })(BABYLON || (BABYLON = {}));
  73295. //# sourceMappingURL=babylon.rayHelper.js.map
  73296. var BABYLON;
  73297. (function (BABYLON) {
  73298. // load the inspector using require, if not present in the global namespace.
  73299. var DebugLayer = /** @class */ (function () {
  73300. function DebugLayer(scene) {
  73301. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73302. this._scene = scene;
  73303. // load inspector using require, if it doesn't exist on the global namespace.
  73304. }
  73305. /** Creates the inspector window. */
  73306. DebugLayer.prototype._createInspector = function (config) {
  73307. if (config === void 0) { config = {}; }
  73308. var popup = config.popup || false;
  73309. var initialTab = config.initialTab || 0;
  73310. var parentElement = config.parentElement || null;
  73311. if (!this._inspector) {
  73312. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73313. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73314. } // else nothing to do,; instance is already existing
  73315. };
  73316. DebugLayer.prototype.isVisible = function () {
  73317. if (!this._inspector) {
  73318. return false;
  73319. }
  73320. return true;
  73321. };
  73322. DebugLayer.prototype.hide = function () {
  73323. if (this._inspector) {
  73324. try {
  73325. this._inspector.dispose();
  73326. }
  73327. catch (e) {
  73328. // If the inspector has been removed directly from the inspector tool
  73329. }
  73330. this._inspector = null;
  73331. }
  73332. };
  73333. DebugLayer.prototype.show = function (config) {
  73334. if (config === void 0) { config = {}; }
  73335. if (typeof this.BJSINSPECTOR == 'undefined') {
  73336. // Load inspector and add it to the DOM
  73337. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73338. }
  73339. else {
  73340. // Otherwise creates the inspector
  73341. this._createInspector(config);
  73342. }
  73343. };
  73344. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73345. return DebugLayer;
  73346. }());
  73347. BABYLON.DebugLayer = DebugLayer;
  73348. })(BABYLON || (BABYLON = {}));
  73349. //# sourceMappingURL=babylon.debugLayer.js.map
  73350. var BABYLON;
  73351. (function (BABYLON) {
  73352. var BoundingBoxRenderer = /** @class */ (function () {
  73353. function BoundingBoxRenderer(scene) {
  73354. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73355. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73356. this.showBackLines = true;
  73357. this.renderList = new BABYLON.SmartArray(32);
  73358. this._vertexBuffers = {};
  73359. this._scene = scene;
  73360. }
  73361. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73362. if (this._colorShader) {
  73363. return;
  73364. }
  73365. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73366. attributes: [BABYLON.VertexBuffer.PositionKind],
  73367. uniforms: ["world", "viewProjection", "color"]
  73368. });
  73369. var engine = this._scene.getEngine();
  73370. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73371. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73372. this._createIndexBuffer();
  73373. };
  73374. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73375. var engine = this._scene.getEngine();
  73376. 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]);
  73377. };
  73378. BoundingBoxRenderer.prototype._rebuild = function () {
  73379. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73380. if (vb) {
  73381. vb._rebuild();
  73382. }
  73383. this._createIndexBuffer();
  73384. };
  73385. BoundingBoxRenderer.prototype.reset = function () {
  73386. this.renderList.reset();
  73387. };
  73388. BoundingBoxRenderer.prototype.render = function () {
  73389. if (this.renderList.length === 0) {
  73390. return;
  73391. }
  73392. this._prepareRessources();
  73393. if (!this._colorShader.isReady()) {
  73394. return;
  73395. }
  73396. var engine = this._scene.getEngine();
  73397. engine.setDepthWrite(false);
  73398. this._colorShader._preBind();
  73399. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73400. var boundingBox = this.renderList.data[boundingBoxIndex];
  73401. var min = boundingBox.minimum;
  73402. var max = boundingBox.maximum;
  73403. var diff = max.subtract(min);
  73404. var median = min.add(diff.scale(0.5));
  73405. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73406. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73407. .multiply(boundingBox.getWorldMatrix());
  73408. // VBOs
  73409. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73410. if (this.showBackLines) {
  73411. // Back
  73412. engine.setDepthFunctionToGreaterOrEqual();
  73413. this._scene.resetCachedMaterial();
  73414. this._colorShader.setColor4("color", this.backColor.toColor4());
  73415. this._colorShader.bind(worldMatrix);
  73416. // Draw order
  73417. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73418. }
  73419. // Front
  73420. engine.setDepthFunctionToLess();
  73421. this._scene.resetCachedMaterial();
  73422. this._colorShader.setColor4("color", this.frontColor.toColor4());
  73423. this._colorShader.bind(worldMatrix);
  73424. // Draw order
  73425. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73426. }
  73427. this._colorShader.unbind();
  73428. engine.setDepthFunctionToLessOrEqual();
  73429. engine.setDepthWrite(true);
  73430. };
  73431. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  73432. this._prepareRessources();
  73433. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  73434. return;
  73435. }
  73436. var engine = this._scene.getEngine();
  73437. engine.setDepthWrite(false);
  73438. engine.setColorWrite(false);
  73439. this._colorShader._preBind();
  73440. var boundingBox = mesh._boundingInfo.boundingBox;
  73441. var min = boundingBox.minimum;
  73442. var max = boundingBox.maximum;
  73443. var diff = max.subtract(min);
  73444. var median = min.add(diff.scale(0.5));
  73445. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73446. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73447. .multiply(boundingBox.getWorldMatrix());
  73448. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73449. engine.setDepthFunctionToLess();
  73450. this._scene.resetCachedMaterial();
  73451. this._colorShader.bind(worldMatrix);
  73452. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73453. this._colorShader.unbind();
  73454. engine.setDepthFunctionToLessOrEqual();
  73455. engine.setDepthWrite(true);
  73456. engine.setColorWrite(true);
  73457. };
  73458. BoundingBoxRenderer.prototype.dispose = function () {
  73459. if (!this._colorShader) {
  73460. return;
  73461. }
  73462. this.renderList.dispose();
  73463. this._colorShader.dispose();
  73464. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73465. if (buffer) {
  73466. buffer.dispose();
  73467. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73468. }
  73469. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73470. };
  73471. return BoundingBoxRenderer;
  73472. }());
  73473. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  73474. })(BABYLON || (BABYLON = {}));
  73475. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  73476. var BABYLON;
  73477. (function (BABYLON) {
  73478. var MorphTarget = /** @class */ (function () {
  73479. function MorphTarget(name, influence) {
  73480. if (influence === void 0) { influence = 0; }
  73481. this.name = name;
  73482. this.animations = new Array();
  73483. this._positions = null;
  73484. this._normals = null;
  73485. this._tangents = null;
  73486. this.onInfluenceChanged = new BABYLON.Observable();
  73487. this.influence = influence;
  73488. }
  73489. Object.defineProperty(MorphTarget.prototype, "influence", {
  73490. get: function () {
  73491. return this._influence;
  73492. },
  73493. set: function (influence) {
  73494. if (this._influence === influence) {
  73495. return;
  73496. }
  73497. var previous = this._influence;
  73498. this._influence = influence;
  73499. if (this.onInfluenceChanged.hasObservers) {
  73500. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  73501. }
  73502. },
  73503. enumerable: true,
  73504. configurable: true
  73505. });
  73506. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  73507. get: function () {
  73508. return !!this._positions;
  73509. },
  73510. enumerable: true,
  73511. configurable: true
  73512. });
  73513. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  73514. get: function () {
  73515. return !!this._normals;
  73516. },
  73517. enumerable: true,
  73518. configurable: true
  73519. });
  73520. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  73521. get: function () {
  73522. return !!this._tangents;
  73523. },
  73524. enumerable: true,
  73525. configurable: true
  73526. });
  73527. MorphTarget.prototype.setPositions = function (data) {
  73528. this._positions = data;
  73529. };
  73530. MorphTarget.prototype.getPositions = function () {
  73531. return this._positions;
  73532. };
  73533. MorphTarget.prototype.setNormals = function (data) {
  73534. this._normals = data;
  73535. };
  73536. MorphTarget.prototype.getNormals = function () {
  73537. return this._normals;
  73538. };
  73539. MorphTarget.prototype.setTangents = function (data) {
  73540. this._tangents = data;
  73541. };
  73542. MorphTarget.prototype.getTangents = function () {
  73543. return this._tangents;
  73544. };
  73545. /**
  73546. * Serializes the current target into a Serialization object.
  73547. * Returns the serialized object.
  73548. */
  73549. MorphTarget.prototype.serialize = function () {
  73550. var serializationObject = {};
  73551. serializationObject.name = this.name;
  73552. serializationObject.influence = this.influence;
  73553. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  73554. if (this.hasNormals) {
  73555. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  73556. }
  73557. if (this.hasTangents) {
  73558. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  73559. }
  73560. // Animations
  73561. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  73562. return serializationObject;
  73563. };
  73564. // Statics
  73565. MorphTarget.Parse = function (serializationObject) {
  73566. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  73567. result.setPositions(serializationObject.positions);
  73568. if (serializationObject.normals) {
  73569. result.setNormals(serializationObject.normals);
  73570. }
  73571. if (serializationObject.tangents) {
  73572. result.setTangents(serializationObject.tangents);
  73573. }
  73574. // Animations
  73575. if (serializationObject.animations) {
  73576. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  73577. var parsedAnimation = serializationObject.animations[animationIndex];
  73578. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73579. }
  73580. }
  73581. return result;
  73582. };
  73583. MorphTarget.FromMesh = function (mesh, name, influence) {
  73584. if (!name) {
  73585. name = mesh.name;
  73586. }
  73587. var result = new MorphTarget(name, influence);
  73588. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73589. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73590. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  73591. }
  73592. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  73593. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  73594. }
  73595. return result;
  73596. };
  73597. return MorphTarget;
  73598. }());
  73599. BABYLON.MorphTarget = MorphTarget;
  73600. })(BABYLON || (BABYLON = {}));
  73601. //# sourceMappingURL=babylon.morphTarget.js.map
  73602. var BABYLON;
  73603. (function (BABYLON) {
  73604. var MorphTargetManager = /** @class */ (function () {
  73605. function MorphTargetManager(scene) {
  73606. if (scene === void 0) { scene = null; }
  73607. this._targets = new Array();
  73608. this._targetObservable = new Array();
  73609. this._activeTargets = new BABYLON.SmartArray(16);
  73610. this._supportsNormals = false;
  73611. this._supportsTangents = false;
  73612. this._vertexCount = 0;
  73613. this._uniqueId = 0;
  73614. this._tempInfluences = new Array();
  73615. if (!scene) {
  73616. scene = BABYLON.Engine.LastCreatedScene;
  73617. }
  73618. this._scene = scene;
  73619. if (this._scene) {
  73620. this._scene.morphTargetManagers.push(this);
  73621. this._uniqueId = this._scene.getUniqueId();
  73622. }
  73623. }
  73624. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  73625. get: function () {
  73626. return this._uniqueId;
  73627. },
  73628. enumerable: true,
  73629. configurable: true
  73630. });
  73631. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  73632. get: function () {
  73633. return this._vertexCount;
  73634. },
  73635. enumerable: true,
  73636. configurable: true
  73637. });
  73638. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  73639. get: function () {
  73640. return this._supportsNormals;
  73641. },
  73642. enumerable: true,
  73643. configurable: true
  73644. });
  73645. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  73646. get: function () {
  73647. return this._supportsTangents;
  73648. },
  73649. enumerable: true,
  73650. configurable: true
  73651. });
  73652. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  73653. get: function () {
  73654. return this._targets.length;
  73655. },
  73656. enumerable: true,
  73657. configurable: true
  73658. });
  73659. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  73660. get: function () {
  73661. return this._activeTargets.length;
  73662. },
  73663. enumerable: true,
  73664. configurable: true
  73665. });
  73666. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  73667. get: function () {
  73668. return this._influences;
  73669. },
  73670. enumerable: true,
  73671. configurable: true
  73672. });
  73673. MorphTargetManager.prototype.getActiveTarget = function (index) {
  73674. return this._activeTargets.data[index];
  73675. };
  73676. MorphTargetManager.prototype.getTarget = function (index) {
  73677. return this._targets[index];
  73678. };
  73679. MorphTargetManager.prototype.addTarget = function (target) {
  73680. var _this = this;
  73681. this._targets.push(target);
  73682. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  73683. _this._syncActiveTargets(needUpdate);
  73684. }));
  73685. this._syncActiveTargets(true);
  73686. };
  73687. MorphTargetManager.prototype.removeTarget = function (target) {
  73688. var index = this._targets.indexOf(target);
  73689. if (index >= 0) {
  73690. this._targets.splice(index, 1);
  73691. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  73692. this._syncActiveTargets(true);
  73693. }
  73694. };
  73695. /**
  73696. * Serializes the current manager into a Serialization object.
  73697. * Returns the serialized object.
  73698. */
  73699. MorphTargetManager.prototype.serialize = function () {
  73700. var serializationObject = {};
  73701. serializationObject.id = this.uniqueId;
  73702. serializationObject.targets = [];
  73703. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73704. var target = _a[_i];
  73705. serializationObject.targets.push(target.serialize());
  73706. }
  73707. return serializationObject;
  73708. };
  73709. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  73710. var influenceCount = 0;
  73711. this._activeTargets.reset();
  73712. this._supportsNormals = true;
  73713. this._supportsTangents = true;
  73714. this._vertexCount = 0;
  73715. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73716. var target = _a[_i];
  73717. this._activeTargets.push(target);
  73718. this._tempInfluences[influenceCount++] = target.influence;
  73719. var positions = target.getPositions();
  73720. if (positions) {
  73721. this._supportsNormals = this._supportsNormals && target.hasNormals;
  73722. this._supportsTangents = this._supportsTangents && target.hasTangents;
  73723. var vertexCount = positions.length / 3;
  73724. if (this._vertexCount === 0) {
  73725. this._vertexCount = vertexCount;
  73726. }
  73727. else if (this._vertexCount !== vertexCount) {
  73728. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  73729. return;
  73730. }
  73731. }
  73732. }
  73733. if (!this._influences || this._influences.length !== influenceCount) {
  73734. this._influences = new Float32Array(influenceCount);
  73735. }
  73736. for (var index = 0; index < influenceCount; index++) {
  73737. this._influences[index] = this._tempInfluences[index];
  73738. }
  73739. if (needUpdate && this._scene) {
  73740. // Flag meshes as dirty to resync with the active targets
  73741. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  73742. var mesh = _c[_b];
  73743. if (mesh.morphTargetManager === this) {
  73744. mesh._syncGeometryWithMorphTargetManager();
  73745. }
  73746. }
  73747. }
  73748. };
  73749. // Statics
  73750. MorphTargetManager.Parse = function (serializationObject, scene) {
  73751. var result = new MorphTargetManager(scene);
  73752. result._uniqueId = serializationObject.id;
  73753. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  73754. var targetData = _a[_i];
  73755. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  73756. }
  73757. return result;
  73758. };
  73759. return MorphTargetManager;
  73760. }());
  73761. BABYLON.MorphTargetManager = MorphTargetManager;
  73762. })(BABYLON || (BABYLON = {}));
  73763. //# sourceMappingURL=babylon.morphTargetManager.js.map
  73764. var BABYLON;
  73765. (function (BABYLON) {
  73766. var Octree = /** @class */ (function () {
  73767. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  73768. if (maxDepth === void 0) { maxDepth = 2; }
  73769. this.maxDepth = maxDepth;
  73770. this.dynamicContent = new Array();
  73771. this._maxBlockCapacity = maxBlockCapacity || 64;
  73772. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  73773. this._creationFunc = creationFunc;
  73774. }
  73775. // Methods
  73776. Octree.prototype.update = function (worldMin, worldMax, entries) {
  73777. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  73778. };
  73779. Octree.prototype.addMesh = function (entry) {
  73780. for (var index = 0; index < this.blocks.length; index++) {
  73781. var block = this.blocks[index];
  73782. block.addEntry(entry);
  73783. }
  73784. };
  73785. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  73786. this._selectionContent.reset();
  73787. for (var index = 0; index < this.blocks.length; index++) {
  73788. var block = this.blocks[index];
  73789. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  73790. }
  73791. if (allowDuplicate) {
  73792. this._selectionContent.concat(this.dynamicContent);
  73793. }
  73794. else {
  73795. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73796. }
  73797. return this._selectionContent;
  73798. };
  73799. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  73800. this._selectionContent.reset();
  73801. for (var index = 0; index < this.blocks.length; index++) {
  73802. var block = this.blocks[index];
  73803. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  73804. }
  73805. if (allowDuplicate) {
  73806. this._selectionContent.concat(this.dynamicContent);
  73807. }
  73808. else {
  73809. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73810. }
  73811. return this._selectionContent;
  73812. };
  73813. Octree.prototype.intersectsRay = function (ray) {
  73814. this._selectionContent.reset();
  73815. for (var index = 0; index < this.blocks.length; index++) {
  73816. var block = this.blocks[index];
  73817. block.intersectsRay(ray, this._selectionContent);
  73818. }
  73819. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73820. return this._selectionContent;
  73821. };
  73822. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  73823. target.blocks = new Array();
  73824. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  73825. // Segmenting space
  73826. for (var x = 0; x < 2; x++) {
  73827. for (var y = 0; y < 2; y++) {
  73828. for (var z = 0; z < 2; z++) {
  73829. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  73830. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  73831. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  73832. block.addEntries(entries);
  73833. target.blocks.push(block);
  73834. }
  73835. }
  73836. }
  73837. };
  73838. Octree.CreationFuncForMeshes = function (entry, block) {
  73839. var boundingInfo = entry.getBoundingInfo();
  73840. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73841. block.entries.push(entry);
  73842. }
  73843. };
  73844. Octree.CreationFuncForSubMeshes = function (entry, block) {
  73845. var boundingInfo = entry.getBoundingInfo();
  73846. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73847. block.entries.push(entry);
  73848. }
  73849. };
  73850. return Octree;
  73851. }());
  73852. BABYLON.Octree = Octree;
  73853. })(BABYLON || (BABYLON = {}));
  73854. //# sourceMappingURL=babylon.octree.js.map
  73855. var BABYLON;
  73856. (function (BABYLON) {
  73857. var OctreeBlock = /** @class */ (function () {
  73858. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  73859. this.entries = new Array();
  73860. this._boundingVectors = new Array();
  73861. this._capacity = capacity;
  73862. this._depth = depth;
  73863. this._maxDepth = maxDepth;
  73864. this._creationFunc = creationFunc;
  73865. this._minPoint = minPoint;
  73866. this._maxPoint = maxPoint;
  73867. this._boundingVectors.push(minPoint.clone());
  73868. this._boundingVectors.push(maxPoint.clone());
  73869. this._boundingVectors.push(minPoint.clone());
  73870. this._boundingVectors[2].x = maxPoint.x;
  73871. this._boundingVectors.push(minPoint.clone());
  73872. this._boundingVectors[3].y = maxPoint.y;
  73873. this._boundingVectors.push(minPoint.clone());
  73874. this._boundingVectors[4].z = maxPoint.z;
  73875. this._boundingVectors.push(maxPoint.clone());
  73876. this._boundingVectors[5].z = minPoint.z;
  73877. this._boundingVectors.push(maxPoint.clone());
  73878. this._boundingVectors[6].x = minPoint.x;
  73879. this._boundingVectors.push(maxPoint.clone());
  73880. this._boundingVectors[7].y = minPoint.y;
  73881. }
  73882. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  73883. // Property
  73884. get: function () {
  73885. return this._capacity;
  73886. },
  73887. enumerable: true,
  73888. configurable: true
  73889. });
  73890. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  73891. get: function () {
  73892. return this._minPoint;
  73893. },
  73894. enumerable: true,
  73895. configurable: true
  73896. });
  73897. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  73898. get: function () {
  73899. return this._maxPoint;
  73900. },
  73901. enumerable: true,
  73902. configurable: true
  73903. });
  73904. // Methods
  73905. OctreeBlock.prototype.addEntry = function (entry) {
  73906. if (this.blocks) {
  73907. for (var index = 0; index < this.blocks.length; index++) {
  73908. var block = this.blocks[index];
  73909. block.addEntry(entry);
  73910. }
  73911. return;
  73912. }
  73913. this._creationFunc(entry, this);
  73914. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  73915. this.createInnerBlocks();
  73916. }
  73917. };
  73918. OctreeBlock.prototype.addEntries = function (entries) {
  73919. for (var index = 0; index < entries.length; index++) {
  73920. var mesh = entries[index];
  73921. this.addEntry(mesh);
  73922. }
  73923. };
  73924. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  73925. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  73926. if (this.blocks) {
  73927. for (var index = 0; index < this.blocks.length; index++) {
  73928. var block = this.blocks[index];
  73929. block.select(frustumPlanes, selection, allowDuplicate);
  73930. }
  73931. return;
  73932. }
  73933. if (allowDuplicate) {
  73934. selection.concat(this.entries);
  73935. }
  73936. else {
  73937. selection.concatWithNoDuplicate(this.entries);
  73938. }
  73939. }
  73940. };
  73941. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  73942. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  73943. if (this.blocks) {
  73944. for (var index = 0; index < this.blocks.length; index++) {
  73945. var block = this.blocks[index];
  73946. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  73947. }
  73948. return;
  73949. }
  73950. if (allowDuplicate) {
  73951. selection.concat(this.entries);
  73952. }
  73953. else {
  73954. selection.concatWithNoDuplicate(this.entries);
  73955. }
  73956. }
  73957. };
  73958. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  73959. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  73960. if (this.blocks) {
  73961. for (var index = 0; index < this.blocks.length; index++) {
  73962. var block = this.blocks[index];
  73963. block.intersectsRay(ray, selection);
  73964. }
  73965. return;
  73966. }
  73967. selection.concatWithNoDuplicate(this.entries);
  73968. }
  73969. };
  73970. OctreeBlock.prototype.createInnerBlocks = function () {
  73971. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  73972. };
  73973. return OctreeBlock;
  73974. }());
  73975. BABYLON.OctreeBlock = OctreeBlock;
  73976. })(BABYLON || (BABYLON = {}));
  73977. //# sourceMappingURL=babylon.octreeBlock.js.map
  73978. var BABYLON;
  73979. (function (BABYLON) {
  73980. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  73981. __extends(VRDistortionCorrectionPostProcess, _super);
  73982. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  73983. var _this = _super.call(this, name, "vrDistortionCorrection", [
  73984. 'LensCenter',
  73985. 'Scale',
  73986. 'ScaleIn',
  73987. 'HmdWarpParam'
  73988. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  73989. _this._isRightEye = isRightEye;
  73990. _this._distortionFactors = vrMetrics.distortionK;
  73991. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  73992. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  73993. _this.adaptScaleToCurrentViewport = true;
  73994. _this.onSizeChangedObservable.add(function () {
  73995. _this.aspectRatio = _this.width * .5 / _this.height;
  73996. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  73997. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  73998. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  73999. });
  74000. _this.onApplyObservable.add(function (effect) {
  74001. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  74002. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  74003. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  74004. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  74005. });
  74006. return _this;
  74007. }
  74008. return VRDistortionCorrectionPostProcess;
  74009. }(BABYLON.PostProcess));
  74010. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  74011. })(BABYLON || (BABYLON = {}));
  74012. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  74013. var BABYLON;
  74014. (function (BABYLON) {
  74015. var AnaglyphPostProcess = /** @class */ (function (_super) {
  74016. __extends(AnaglyphPostProcess, _super);
  74017. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  74018. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  74019. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74020. _this.onApplyObservable.add(function (effect) {
  74021. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  74022. });
  74023. return _this;
  74024. }
  74025. return AnaglyphPostProcess;
  74026. }(BABYLON.PostProcess));
  74027. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  74028. })(BABYLON || (BABYLON = {}));
  74029. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  74030. var BABYLON;
  74031. (function (BABYLON) {
  74032. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  74033. __extends(StereoscopicInterlacePostProcess, _super);
  74034. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  74035. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  74036. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74037. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74038. _this.onSizeChangedObservable.add(function () {
  74039. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74040. });
  74041. _this.onApplyObservable.add(function (effect) {
  74042. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  74043. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  74044. });
  74045. return _this;
  74046. }
  74047. return StereoscopicInterlacePostProcess;
  74048. }(BABYLON.PostProcess));
  74049. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  74050. })(BABYLON || (BABYLON = {}));
  74051. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  74052. var BABYLON;
  74053. (function (BABYLON) {
  74054. /**
  74055. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  74056. * Screen rotation is taken into account.
  74057. */
  74058. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  74059. function FreeCameraDeviceOrientationInput() {
  74060. var _this = this;
  74061. this._screenOrientationAngle = 0;
  74062. this._screenQuaternion = new BABYLON.Quaternion();
  74063. this._alpha = 0;
  74064. this._beta = 0;
  74065. this._gamma = 0;
  74066. this._orientationChanged = function () {
  74067. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  74068. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  74069. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  74070. };
  74071. this._deviceOrientation = function (evt) {
  74072. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  74073. _this._beta = evt.beta !== null ? evt.beta : 0;
  74074. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  74075. };
  74076. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  74077. this._orientationChanged();
  74078. }
  74079. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  74080. get: function () {
  74081. return this._camera;
  74082. },
  74083. set: function (camera) {
  74084. this._camera = camera;
  74085. if (this._camera != null && !this._camera.rotationQuaternion) {
  74086. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  74087. }
  74088. },
  74089. enumerable: true,
  74090. configurable: true
  74091. });
  74092. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74093. window.addEventListener("orientationchange", this._orientationChanged);
  74094. window.addEventListener("deviceorientation", this._deviceOrientation);
  74095. //In certain cases, the attach control is called AFTER orientation was changed,
  74096. //So this is needed.
  74097. this._orientationChanged();
  74098. };
  74099. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  74100. window.removeEventListener("orientationchange", this._orientationChanged);
  74101. window.removeEventListener("deviceorientation", this._deviceOrientation);
  74102. };
  74103. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  74104. //if no device orientation provided, don't update the rotation.
  74105. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  74106. if (!this._alpha)
  74107. return;
  74108. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  74109. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  74110. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  74111. //Mirror on XY Plane
  74112. this._camera.rotationQuaternion.z *= -1;
  74113. this._camera.rotationQuaternion.w *= -1;
  74114. };
  74115. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  74116. return "FreeCameraDeviceOrientationInput";
  74117. };
  74118. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  74119. return "deviceOrientation";
  74120. };
  74121. return FreeCameraDeviceOrientationInput;
  74122. }());
  74123. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  74124. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  74125. })(BABYLON || (BABYLON = {}));
  74126. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  74127. var BABYLON;
  74128. (function (BABYLON) {
  74129. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  74130. function ArcRotateCameraVRDeviceOrientationInput() {
  74131. this.alphaCorrection = 1;
  74132. this.betaCorrection = 1;
  74133. this.gammaCorrection = 1;
  74134. this._alpha = 0;
  74135. this._gamma = 0;
  74136. this._dirty = false;
  74137. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  74138. }
  74139. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74140. this.camera.attachControl(element, noPreventDefault);
  74141. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  74142. };
  74143. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  74144. if (evt.alpha !== null) {
  74145. this._alpha = +evt.alpha | 0;
  74146. }
  74147. if (evt.gamma !== null) {
  74148. this._gamma = +evt.gamma | 0;
  74149. }
  74150. this._dirty = true;
  74151. };
  74152. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  74153. if (this._dirty) {
  74154. this._dirty = false;
  74155. if (this._gamma < 0) {
  74156. this._gamma = 180 + this._gamma;
  74157. }
  74158. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  74159. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  74160. }
  74161. };
  74162. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  74163. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  74164. };
  74165. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  74166. return "ArcRotateCameraVRDeviceOrientationInput";
  74167. };
  74168. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  74169. return "VRDeviceOrientation";
  74170. };
  74171. return ArcRotateCameraVRDeviceOrientationInput;
  74172. }());
  74173. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  74174. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  74175. })(BABYLON || (BABYLON = {}));
  74176. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74177. var BABYLON;
  74178. (function (BABYLON) {
  74179. var VRCameraMetrics = /** @class */ (function () {
  74180. function VRCameraMetrics() {
  74181. this.compensateDistortion = true;
  74182. }
  74183. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74184. get: function () {
  74185. return this.hResolution / (2 * this.vResolution);
  74186. },
  74187. enumerable: true,
  74188. configurable: true
  74189. });
  74190. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74191. get: function () {
  74192. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74193. },
  74194. enumerable: true,
  74195. configurable: true
  74196. });
  74197. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74198. get: function () {
  74199. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74200. var h = (4 * meters) / this.hScreenSize;
  74201. return BABYLON.Matrix.Translation(h, 0, 0);
  74202. },
  74203. enumerable: true,
  74204. configurable: true
  74205. });
  74206. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74207. get: function () {
  74208. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74209. var h = (4 * meters) / this.hScreenSize;
  74210. return BABYLON.Matrix.Translation(-h, 0, 0);
  74211. },
  74212. enumerable: true,
  74213. configurable: true
  74214. });
  74215. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74216. get: function () {
  74217. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74218. },
  74219. enumerable: true,
  74220. configurable: true
  74221. });
  74222. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74223. get: function () {
  74224. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74225. },
  74226. enumerable: true,
  74227. configurable: true
  74228. });
  74229. VRCameraMetrics.GetDefault = function () {
  74230. var result = new VRCameraMetrics();
  74231. result.hResolution = 1280;
  74232. result.vResolution = 800;
  74233. result.hScreenSize = 0.149759993;
  74234. result.vScreenSize = 0.0935999975;
  74235. result.vScreenCenter = 0.0467999987;
  74236. result.eyeToScreenDistance = 0.0410000011;
  74237. result.lensSeparationDistance = 0.0635000020;
  74238. result.interpupillaryDistance = 0.0640000030;
  74239. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74240. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74241. result.postProcessScaleFactor = 1.714605507808412;
  74242. result.lensCenterOffset = 0.151976421;
  74243. return result;
  74244. };
  74245. return VRCameraMetrics;
  74246. }());
  74247. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74248. })(BABYLON || (BABYLON = {}));
  74249. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74250. var BABYLON;
  74251. (function (BABYLON) {
  74252. /**
  74253. * This represents a WebVR camera.
  74254. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  74255. * @example http://doc.babylonjs.com/how_to/webvr_camera
  74256. */
  74257. var WebVRFreeCamera = /** @class */ (function (_super) {
  74258. __extends(WebVRFreeCamera, _super);
  74259. /**
  74260. * Instantiates a WebVRFreeCamera.
  74261. * @param name The name of the WebVRFreeCamera
  74262. * @param position The starting anchor position for the camera
  74263. * @param scene The scene the camera belongs to
  74264. * @param webVROptions a set of customizable options for the webVRCamera
  74265. */
  74266. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74267. if (webVROptions === void 0) { webVROptions = {}; }
  74268. var _this = _super.call(this, name, position, scene) || this;
  74269. _this.webVROptions = webVROptions;
  74270. /**
  74271. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  74272. */
  74273. _this._vrDevice = null;
  74274. /**
  74275. * The rawPose of the vrDevice.
  74276. */
  74277. _this.rawPose = null;
  74278. _this._specsVersion = "1.1";
  74279. _this._attached = false;
  74280. _this._descendants = [];
  74281. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74282. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74283. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74284. _this._standingMatrix = null;
  74285. /**
  74286. * Represents device position in babylon space.
  74287. */
  74288. _this.devicePosition = BABYLON.Vector3.Zero();
  74289. /**
  74290. * Represents device rotation in babylon space.
  74291. */
  74292. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74293. /**
  74294. * The scale of the device to be used when translating from device space to babylon space.
  74295. */
  74296. _this.deviceScaleFactor = 1;
  74297. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74298. _this._worldToDevice = BABYLON.Matrix.Identity();
  74299. /**
  74300. * References to the webVR controllers for the vrDevice.
  74301. */
  74302. _this.controllers = [];
  74303. /**
  74304. * Emits an event when a controller is attached.
  74305. */
  74306. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74307. /**
  74308. * Emits an event when a controller's mesh has been loaded;
  74309. */
  74310. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74311. /**
  74312. * If the rig cameras be used as parent instead of this camera.
  74313. */
  74314. _this.rigParenting = true;
  74315. _this._defaultHeight = undefined;
  74316. _this._workingVector = BABYLON.Vector3.Zero();
  74317. _this._oneVector = BABYLON.Vector3.One();
  74318. _this._workingMatrix = BABYLON.Matrix.Identity();
  74319. _this._cache.position = BABYLON.Vector3.Zero();
  74320. if (webVROptions.defaultHeight) {
  74321. _this._defaultHeight = webVROptions.defaultHeight;
  74322. _this.position.y = _this._defaultHeight;
  74323. }
  74324. _this.minZ = 0.1;
  74325. //legacy support - the compensation boolean was removed.
  74326. if (arguments.length === 5) {
  74327. _this.webVROptions = arguments[4];
  74328. }
  74329. // default webVR options
  74330. if (_this.webVROptions.trackPosition == undefined) {
  74331. _this.webVROptions.trackPosition = true;
  74332. }
  74333. if (_this.webVROptions.controllerMeshes == undefined) {
  74334. _this.webVROptions.controllerMeshes = true;
  74335. }
  74336. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74337. _this.webVROptions.defaultLightingOnControllers = true;
  74338. }
  74339. _this.rotationQuaternion = new BABYLON.Quaternion();
  74340. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74341. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74342. }
  74343. //enable VR
  74344. var engine = _this.getEngine();
  74345. _this._onVREnabled = function (success) { if (success) {
  74346. _this.initControllers();
  74347. } };
  74348. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74349. engine.initWebVR().add(function (event) {
  74350. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74351. return;
  74352. }
  74353. _this._vrDevice = event.vrDisplay;
  74354. //reset the rig parameters.
  74355. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74356. if (_this._attached) {
  74357. _this.getEngine().enableVR();
  74358. }
  74359. });
  74360. if (typeof (VRFrameData) !== "undefined")
  74361. _this._frameData = new VRFrameData();
  74362. /**
  74363. * The idea behind the following lines:
  74364. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74365. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74366. * the second will not show it correctly.
  74367. *
  74368. * To solve this - each object that has the camera as parent will be added to a protected array.
  74369. * When the rig camera renders, it will take this array and set all of those to be its children.
  74370. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74371. * Amazing!
  74372. */
  74373. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74374. if (camera.parent === _this && _this.rigParenting) {
  74375. _this._descendants = _this.getDescendants(true, function (n) {
  74376. // don't take the cameras or the controllers!
  74377. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74378. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74379. return !isController && !isRigCamera;
  74380. });
  74381. _this._descendants.forEach(function (node) {
  74382. node.parent = camera;
  74383. });
  74384. }
  74385. });
  74386. scene.onAfterCameraRenderObservable.add(function (camera) {
  74387. if (camera.parent === _this && _this.rigParenting) {
  74388. _this._descendants.forEach(function (node) {
  74389. node.parent = _this;
  74390. });
  74391. }
  74392. });
  74393. return _this;
  74394. }
  74395. /**
  74396. * Gets the device distance from the ground.
  74397. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  74398. */
  74399. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  74400. if (this._standingMatrix && this._defaultHeight === undefined) {
  74401. // Add standing matrix offset to get real offset from ground in room
  74402. this._standingMatrix.getTranslationToRef(this._workingVector);
  74403. return this._deviceRoomPosition.y + this._workingVector.y;
  74404. }
  74405. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74406. return this._defaultHeight || 0;
  74407. };
  74408. /**
  74409. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  74410. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  74411. */
  74412. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  74413. var _this = this;
  74414. if (callback === void 0) { callback = function (bool) { }; }
  74415. // Use standing matrix if available
  74416. if (!navigator || !navigator.getVRDisplays) {
  74417. callback(false);
  74418. }
  74419. else {
  74420. navigator.getVRDisplays().then(function (displays) {
  74421. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  74422. callback(false);
  74423. }
  74424. else {
  74425. _this._standingMatrix = new BABYLON.Matrix();
  74426. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  74427. if (!_this.getScene().useRightHandedSystem) {
  74428. [2, 6, 8, 9, 14].forEach(function (num) {
  74429. if (_this._standingMatrix) {
  74430. _this._standingMatrix.m[num] *= -1;
  74431. }
  74432. });
  74433. }
  74434. callback(true);
  74435. }
  74436. });
  74437. }
  74438. };
  74439. /**
  74440. * Disposes the camera
  74441. */
  74442. WebVRFreeCamera.prototype.dispose = function () {
  74443. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  74444. _super.prototype.dispose.call(this);
  74445. };
  74446. /**
  74447. * Gets a vrController by name.
  74448. * @param name The name of the controller to retreive
  74449. * @returns the controller matching the name specified or null if not found
  74450. */
  74451. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  74452. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  74453. var gp = _a[_i];
  74454. if (gp.hand === name) {
  74455. return gp;
  74456. }
  74457. }
  74458. return null;
  74459. };
  74460. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  74461. /**
  74462. * The controller corrisponding to the users left hand.
  74463. */
  74464. get: function () {
  74465. if (!this._leftController) {
  74466. this._leftController = this.getControllerByName("left");
  74467. }
  74468. return this._leftController;
  74469. },
  74470. enumerable: true,
  74471. configurable: true
  74472. });
  74473. ;
  74474. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  74475. /**
  74476. * The controller corrisponding to the users right hand.
  74477. */
  74478. get: function () {
  74479. if (!this._rightController) {
  74480. this._rightController = this.getControllerByName("right");
  74481. }
  74482. return this._rightController;
  74483. },
  74484. enumerable: true,
  74485. configurable: true
  74486. });
  74487. ;
  74488. /**
  74489. * Casts a ray forward from the vrCamera's gaze.
  74490. * @param length Length of the ray (default: 100)
  74491. * @returns the ray corrisponding to the gaze
  74492. */
  74493. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  74494. if (length === void 0) { length = 100; }
  74495. if (this.leftCamera) {
  74496. // Use left eye to avoid computation to compute center on every call
  74497. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  74498. }
  74499. else {
  74500. return _super.prototype.getForwardRay.call(this, length);
  74501. }
  74502. };
  74503. /**
  74504. * Updates the camera based on device's frame data
  74505. */
  74506. WebVRFreeCamera.prototype._checkInputs = function () {
  74507. if (this._vrDevice && this._vrDevice.isPresenting) {
  74508. this._vrDevice.getFrameData(this._frameData);
  74509. this.updateFromDevice(this._frameData.pose);
  74510. }
  74511. _super.prototype._checkInputs.call(this);
  74512. };
  74513. /**
  74514. * Updates the poseControlled values based on the input device pose.
  74515. * @param poseData Pose coming from the device
  74516. */
  74517. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  74518. if (poseData && poseData.orientation) {
  74519. this.rawPose = poseData;
  74520. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  74521. if (this.getScene().useRightHandedSystem) {
  74522. this._deviceRoomRotationQuaternion.z *= -1;
  74523. this._deviceRoomRotationQuaternion.w *= -1;
  74524. }
  74525. if (this.webVROptions.trackPosition && this.rawPose.position) {
  74526. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  74527. if (this.getScene().useRightHandedSystem) {
  74528. this._deviceRoomPosition.z *= -1;
  74529. }
  74530. }
  74531. }
  74532. };
  74533. /**
  74534. * WebVR's attach control will start broadcasting frames to the device.
  74535. * Note that in certain browsers (chrome for example) this function must be called
  74536. * within a user-interaction callback. Example:
  74537. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  74538. *
  74539. * @param element html element to attach the vrDevice to
  74540. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  74541. */
  74542. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  74543. _super.prototype.attachControl.call(this, element, noPreventDefault);
  74544. this._attached = true;
  74545. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  74546. if (this._vrDevice) {
  74547. this.getEngine().enableVR();
  74548. }
  74549. };
  74550. /**
  74551. * Detaches the camera from the html element and disables VR
  74552. *
  74553. * @param element html element to detach from
  74554. */
  74555. WebVRFreeCamera.prototype.detachControl = function (element) {
  74556. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74557. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74558. _super.prototype.detachControl.call(this, element);
  74559. this._attached = false;
  74560. this.getEngine().disableVR();
  74561. };
  74562. /**
  74563. * @returns the name of this class
  74564. */
  74565. WebVRFreeCamera.prototype.getClassName = function () {
  74566. return "WebVRFreeCamera";
  74567. };
  74568. /**
  74569. * Calls resetPose on the vrDisplay
  74570. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  74571. */
  74572. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  74573. //uses the vrDisplay's "resetPose()".
  74574. //pitch and roll won't be affected.
  74575. this._vrDevice.resetPose();
  74576. };
  74577. /**
  74578. * Updates the rig cameras (left and right eye)
  74579. */
  74580. WebVRFreeCamera.prototype._updateRigCameras = function () {
  74581. var camLeft = this._rigCameras[0];
  74582. var camRight = this._rigCameras[1];
  74583. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74584. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74585. camLeft.position.copyFrom(this._deviceRoomPosition);
  74586. camRight.position.copyFrom(this._deviceRoomPosition);
  74587. };
  74588. /**
  74589. * Updates the cached values of the camera
  74590. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  74591. */
  74592. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  74593. var _this = this;
  74594. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  74595. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  74596. if (!this.updateCacheCalled) {
  74597. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  74598. this.updateCacheCalled = true;
  74599. this.update();
  74600. }
  74601. // Set working vector to the device position in room space rotated by the new rotation
  74602. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  74603. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  74604. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  74605. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  74606. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  74607. // Add translation from anchor position
  74608. this._deviceToWorld.getTranslationToRef(this._workingVector);
  74609. this._workingVector.addInPlace(this.position);
  74610. this._workingVector.subtractInPlace(this._cache.position);
  74611. this._deviceToWorld.setTranslation(this._workingVector);
  74612. // Set an inverted matrix to be used when updating the camera
  74613. this._deviceToWorld.invertToRef(this._worldToDevice);
  74614. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  74615. this.controllers.forEach(function (controller) {
  74616. controller._deviceToWorld = _this._deviceToWorld;
  74617. controller.update();
  74618. });
  74619. }
  74620. if (!ignoreParentClass) {
  74621. _super.prototype._updateCache.call(this);
  74622. }
  74623. this.updateCacheCalled = false;
  74624. };
  74625. /**
  74626. * Updates the current device position and rotation in the babylon world
  74627. */
  74628. WebVRFreeCamera.prototype.update = function () {
  74629. // Get current device position in babylon world
  74630. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  74631. // Get current device rotation in babylon world
  74632. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  74633. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  74634. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74635. _super.prototype.update.call(this);
  74636. };
  74637. /**
  74638. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  74639. * @returns an identity matrix
  74640. */
  74641. WebVRFreeCamera.prototype._getViewMatrix = function () {
  74642. return BABYLON.Matrix.Identity();
  74643. };
  74644. /**
  74645. * This function is called by the two RIG cameras.
  74646. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  74647. */
  74648. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  74649. var _this = this;
  74650. //WebVR 1.1
  74651. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  74652. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  74653. if (!this.getScene().useRightHandedSystem) {
  74654. [2, 6, 8, 9, 14].forEach(function (num) {
  74655. _this._webvrViewMatrix.m[num] *= -1;
  74656. });
  74657. }
  74658. // update the camera rotation matrix
  74659. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  74660. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  74661. // Computing target and final matrix
  74662. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  74663. var parentCamera = this._cameraRigParams["parentCamera"];
  74664. // should the view matrix be updated with scale and position offset?
  74665. if (parentCamera.deviceScaleFactor !== 1) {
  74666. this._webvrViewMatrix.invert();
  74667. // scale the position, if set
  74668. if (parentCamera.deviceScaleFactor) {
  74669. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  74670. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  74671. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  74672. }
  74673. this._webvrViewMatrix.invert();
  74674. }
  74675. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  74676. return this._webvrViewMatrix;
  74677. };
  74678. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  74679. var _this = this;
  74680. var parentCamera = this.parent;
  74681. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  74682. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  74683. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  74684. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  74685. //babylon compatible matrix
  74686. if (!this.getScene().useRightHandedSystem) {
  74687. [8, 9, 10, 11].forEach(function (num) {
  74688. _this._projectionMatrix.m[num] *= -1;
  74689. });
  74690. }
  74691. return this._projectionMatrix;
  74692. };
  74693. /**
  74694. * Initializes the controllers and their meshes
  74695. */
  74696. WebVRFreeCamera.prototype.initControllers = function () {
  74697. var _this = this;
  74698. this.controllers = [];
  74699. var manager = this.getScene().gamepadManager;
  74700. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74701. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74702. var webVrController = gamepad;
  74703. if (webVrController.defaultModel) {
  74704. webVrController.defaultModel.setEnabled(false);
  74705. }
  74706. if (webVrController.hand === "right") {
  74707. _this._rightController = null;
  74708. }
  74709. if (webVrController.hand === "left") {
  74710. _this._rightController = null;
  74711. }
  74712. var controllerIndex = _this.controllers.indexOf(webVrController);
  74713. if (controllerIndex !== -1) {
  74714. _this.controllers.splice(controllerIndex, 1);
  74715. }
  74716. }
  74717. });
  74718. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74719. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74720. var webVrController_1 = gamepad;
  74721. webVrController_1._deviceToWorld = _this._deviceToWorld;
  74722. if (_this.webVROptions.controllerMeshes) {
  74723. if (webVrController_1.defaultModel) {
  74724. webVrController_1.defaultModel.setEnabled(true);
  74725. }
  74726. else {
  74727. // Load the meshes
  74728. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  74729. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  74730. if (_this.webVROptions.defaultLightingOnControllers) {
  74731. if (!_this._lightOnControllers) {
  74732. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  74733. }
  74734. var activateLightOnSubMeshes_1 = function (mesh, light) {
  74735. var children = mesh.getChildren();
  74736. if (children.length !== 0) {
  74737. children.forEach(function (mesh) {
  74738. light.includedOnlyMeshes.push(mesh);
  74739. activateLightOnSubMeshes_1(mesh, light);
  74740. });
  74741. }
  74742. };
  74743. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  74744. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  74745. }
  74746. });
  74747. }
  74748. }
  74749. webVrController_1.attachToPoseControlledCamera(_this);
  74750. // since this is async - sanity check. Is the controller already stored?
  74751. if (_this.controllers.indexOf(webVrController_1) === -1) {
  74752. //add to the controllers array
  74753. _this.controllers.push(webVrController_1);
  74754. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  74755. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  74756. // So we're overriding setting left & right manually to be sure
  74757. var firstViveWandDetected = false;
  74758. for (var i = 0; i < _this.controllers.length; i++) {
  74759. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74760. if (!firstViveWandDetected) {
  74761. firstViveWandDetected = true;
  74762. _this.controllers[i].hand = "left";
  74763. }
  74764. else {
  74765. _this.controllers[i].hand = "right";
  74766. }
  74767. }
  74768. }
  74769. //did we find enough controllers? Great! let the developer know.
  74770. if (_this.controllers.length >= 2) {
  74771. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  74772. }
  74773. }
  74774. }
  74775. });
  74776. };
  74777. return WebVRFreeCamera;
  74778. }(BABYLON.FreeCamera));
  74779. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  74780. })(BABYLON || (BABYLON = {}));
  74781. //# sourceMappingURL=babylon.webVRCamera.js.map
  74782. var BABYLON;
  74783. (function (BABYLON) {
  74784. // We're mainly based on the logic defined into the FreeCamera code
  74785. /**
  74786. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  74787. * being tilted forward or back and left or right.
  74788. */
  74789. var DeviceOrientationCamera = /** @class */ (function (_super) {
  74790. __extends(DeviceOrientationCamera, _super);
  74791. /**
  74792. * Creates a new device orientation camera. @see DeviceOrientationCamera
  74793. * @param name The name of the camera
  74794. * @param position The start position camera
  74795. * @param scene The scene the camera belongs to
  74796. */
  74797. function DeviceOrientationCamera(name, position, scene) {
  74798. var _this = _super.call(this, name, position, scene) || this;
  74799. _this._quaternionCache = new BABYLON.Quaternion();
  74800. _this.inputs.addDeviceOrientation();
  74801. return _this;
  74802. }
  74803. /**
  74804. * Gets the current instance class name ("DeviceOrientationCamera").
  74805. * This helps avoiding instanceof at run time.
  74806. * @returns the class name
  74807. */
  74808. DeviceOrientationCamera.prototype.getClassName = function () {
  74809. return "DeviceOrientationCamera";
  74810. };
  74811. /**
  74812. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  74813. */
  74814. DeviceOrientationCamera.prototype._checkInputs = function () {
  74815. _super.prototype._checkInputs.call(this);
  74816. this._quaternionCache.copyFrom(this.rotationQuaternion);
  74817. if (this._initialQuaternion) {
  74818. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74819. }
  74820. };
  74821. /**
  74822. * Reset the camera to its default orientation on the specified axis only.
  74823. * @param axis The axis to reset
  74824. */
  74825. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  74826. var _this = this;
  74827. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  74828. //can only work if this camera has a rotation quaternion already.
  74829. if (!this.rotationQuaternion)
  74830. return;
  74831. if (!this._initialQuaternion) {
  74832. this._initialQuaternion = new BABYLON.Quaternion();
  74833. }
  74834. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  74835. ['x', 'y', 'z'].forEach(function (axisName) {
  74836. if (!axis[axisName]) {
  74837. _this._initialQuaternion[axisName] = 0;
  74838. }
  74839. else {
  74840. _this._initialQuaternion[axisName] *= -1;
  74841. }
  74842. });
  74843. this._initialQuaternion.normalize();
  74844. //force rotation update
  74845. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74846. };
  74847. return DeviceOrientationCamera;
  74848. }(BABYLON.FreeCamera));
  74849. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  74850. })(BABYLON || (BABYLON = {}));
  74851. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  74852. var BABYLON;
  74853. (function (BABYLON) {
  74854. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  74855. __extends(VRDeviceOrientationFreeCamera, _super);
  74856. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74857. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74858. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74859. var _this = _super.call(this, name, position, scene) || this;
  74860. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74861. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74862. return _this;
  74863. }
  74864. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  74865. return "VRDeviceOrientationFreeCamera";
  74866. };
  74867. return VRDeviceOrientationFreeCamera;
  74868. }(BABYLON.DeviceOrientationCamera));
  74869. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  74870. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  74871. __extends(VRDeviceOrientationGamepadCamera, _super);
  74872. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74873. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74874. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74875. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  74876. _this.inputs.addGamepad();
  74877. return _this;
  74878. }
  74879. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  74880. return "VRDeviceOrientationGamepadCamera";
  74881. };
  74882. return VRDeviceOrientationGamepadCamera;
  74883. }(VRDeviceOrientationFreeCamera));
  74884. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  74885. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  74886. __extends(VRDeviceOrientationArcRotateCamera, _super);
  74887. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  74888. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74889. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74890. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74891. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74892. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74893. _this.inputs.addVRDeviceOrientation();
  74894. return _this;
  74895. }
  74896. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  74897. return "VRDeviceOrientationArcRotateCamera";
  74898. };
  74899. return VRDeviceOrientationArcRotateCamera;
  74900. }(BABYLON.ArcRotateCamera));
  74901. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  74902. })(BABYLON || (BABYLON = {}));
  74903. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  74904. var BABYLON;
  74905. (function (BABYLON) {
  74906. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  74907. __extends(AnaglyphFreeCamera, _super);
  74908. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  74909. var _this = _super.call(this, name, position, scene) || this;
  74910. _this.interaxialDistance = interaxialDistance;
  74911. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74912. return _this;
  74913. }
  74914. AnaglyphFreeCamera.prototype.getClassName = function () {
  74915. return "AnaglyphFreeCamera";
  74916. };
  74917. return AnaglyphFreeCamera;
  74918. }(BABYLON.FreeCamera));
  74919. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  74920. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  74921. __extends(AnaglyphArcRotateCamera, _super);
  74922. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  74923. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74924. _this.interaxialDistance = interaxialDistance;
  74925. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74926. return _this;
  74927. }
  74928. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  74929. return "AnaglyphArcRotateCamera";
  74930. };
  74931. return AnaglyphArcRotateCamera;
  74932. }(BABYLON.ArcRotateCamera));
  74933. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  74934. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  74935. __extends(AnaglyphGamepadCamera, _super);
  74936. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  74937. var _this = _super.call(this, name, position, scene) || this;
  74938. _this.interaxialDistance = interaxialDistance;
  74939. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74940. return _this;
  74941. }
  74942. AnaglyphGamepadCamera.prototype.getClassName = function () {
  74943. return "AnaglyphGamepadCamera";
  74944. };
  74945. return AnaglyphGamepadCamera;
  74946. }(BABYLON.GamepadCamera));
  74947. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  74948. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  74949. __extends(AnaglyphUniversalCamera, _super);
  74950. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  74951. var _this = _super.call(this, name, position, scene) || this;
  74952. _this.interaxialDistance = interaxialDistance;
  74953. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74954. return _this;
  74955. }
  74956. AnaglyphUniversalCamera.prototype.getClassName = function () {
  74957. return "AnaglyphUniversalCamera";
  74958. };
  74959. return AnaglyphUniversalCamera;
  74960. }(BABYLON.UniversalCamera));
  74961. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  74962. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  74963. __extends(StereoscopicFreeCamera, _super);
  74964. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74965. var _this = _super.call(this, name, position, scene) || this;
  74966. _this.interaxialDistance = interaxialDistance;
  74967. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74968. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74969. return _this;
  74970. }
  74971. StereoscopicFreeCamera.prototype.getClassName = function () {
  74972. return "StereoscopicFreeCamera";
  74973. };
  74974. return StereoscopicFreeCamera;
  74975. }(BABYLON.FreeCamera));
  74976. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  74977. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  74978. __extends(StereoscopicArcRotateCamera, _super);
  74979. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  74980. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74981. _this.interaxialDistance = interaxialDistance;
  74982. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74983. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74984. return _this;
  74985. }
  74986. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  74987. return "StereoscopicArcRotateCamera";
  74988. };
  74989. return StereoscopicArcRotateCamera;
  74990. }(BABYLON.ArcRotateCamera));
  74991. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  74992. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  74993. __extends(StereoscopicGamepadCamera, _super);
  74994. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74995. var _this = _super.call(this, name, position, scene) || this;
  74996. _this.interaxialDistance = interaxialDistance;
  74997. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74998. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74999. return _this;
  75000. }
  75001. StereoscopicGamepadCamera.prototype.getClassName = function () {
  75002. return "StereoscopicGamepadCamera";
  75003. };
  75004. return StereoscopicGamepadCamera;
  75005. }(BABYLON.GamepadCamera));
  75006. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  75007. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  75008. __extends(StereoscopicUniversalCamera, _super);
  75009. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75010. var _this = _super.call(this, name, position, scene) || this;
  75011. _this.interaxialDistance = interaxialDistance;
  75012. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75013. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75014. return _this;
  75015. }
  75016. StereoscopicUniversalCamera.prototype.getClassName = function () {
  75017. return "StereoscopicUniversalCamera";
  75018. };
  75019. return StereoscopicUniversalCamera;
  75020. }(BABYLON.UniversalCamera));
  75021. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  75022. })(BABYLON || (BABYLON = {}));
  75023. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  75024. var BABYLON;
  75025. (function (BABYLON) {
  75026. /**
  75027. * Helps to quickly add VR support to an existing scene.
  75028. * See http://doc.babylonjs.com/how_to/webvr_helper
  75029. */
  75030. var VRExperienceHelper = /** @class */ (function () {
  75031. /**
  75032. * Instantiates a VRExperienceHelper.
  75033. * Helps to quickly add VR support to an existing scene.
  75034. * @param scene The scene the VRExperienceHelper belongs to.
  75035. * @param webVROptions Options to modify the vr experience helper's behavior.
  75036. */
  75037. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  75038. if (webVROptions === void 0) { webVROptions = {}; }
  75039. var _this = this;
  75040. this.webVROptions = webVROptions;
  75041. // Can the system support WebVR, even if a headset isn't plugged in?
  75042. this._webVRsupported = false;
  75043. // If WebVR is supported, is a headset plugged in and are we ready to present?
  75044. this._webVRready = false;
  75045. // Are we waiting for the requestPresent callback to complete?
  75046. this._webVRrequesting = false;
  75047. // Are we presenting to the headset right now?
  75048. this._webVRpresenting = false;
  75049. // Are we presenting in the fullscreen fallback?
  75050. this._fullscreenVRpresenting = false;
  75051. /**
  75052. * Observable raised when entering VR.
  75053. */
  75054. this.onEnteringVRObservable = new BABYLON.Observable();
  75055. /**
  75056. * Observable raised when exiting VR.
  75057. */
  75058. this.onExitingVRObservable = new BABYLON.Observable();
  75059. /**
  75060. * Observable raised when controller mesh is loaded.
  75061. */
  75062. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75063. this._useCustomVRButton = false;
  75064. this._teleportationRequested = false;
  75065. this._teleportationEnabledOnLeftController = false;
  75066. this._teleportationEnabledOnRightController = false;
  75067. this._interactionsEnabledOnLeftController = false;
  75068. this._interactionsEnabledOnRightController = false;
  75069. this._leftControllerReady = false;
  75070. this._rightControllerReady = false;
  75071. this._floorMeshesCollection = [];
  75072. this._teleportationAllowed = false;
  75073. this._rotationAllowed = true;
  75074. this._teleportationRequestInitiated = false;
  75075. this._teleportationBackRequestInitiated = false;
  75076. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  75077. this._rotationRightAsked = false;
  75078. this._rotationLeftAsked = false;
  75079. this._isDefaultTeleportationTarget = true;
  75080. this._teleportationFillColor = "#444444";
  75081. this._teleportationBorderColor = "#FFFFFF";
  75082. this._rotationAngle = 0;
  75083. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  75084. this._padSensibilityUp = 0.65;
  75085. this._padSensibilityDown = 0.35;
  75086. /**
  75087. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  75088. */
  75089. this.onNewMeshSelected = new BABYLON.Observable();
  75090. /**
  75091. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  75092. */
  75093. this.onNewMeshPicked = new BABYLON.Observable();
  75094. /**
  75095. * Observable raised before camera teleportation
  75096. */
  75097. this.onBeforeCameraTeleport = new BABYLON.Observable();
  75098. /**
  75099. * Observable raised after camera teleportation
  75100. */
  75101. this.onAfterCameraTeleport = new BABYLON.Observable();
  75102. /**
  75103. * Observable raised when current selected mesh gets unselected
  75104. */
  75105. this.onSelectedMeshUnselected = new BABYLON.Observable();
  75106. /**
  75107. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  75108. */
  75109. this.teleportationEnabled = true;
  75110. this._pointerDownOnMeshAsked = false;
  75111. this._isActionableMesh = false;
  75112. this._teleportationInitialized = false;
  75113. this._interactionsEnabled = false;
  75114. this._interactionsRequested = false;
  75115. this._displayGaze = true;
  75116. this._displayLaserPointer = true;
  75117. this._dpadPressed = true;
  75118. this._onResize = function () {
  75119. _this.moveButtonToBottomRight();
  75120. if (_this._fullscreenVRpresenting && _this._webVRready) {
  75121. _this.exitVR();
  75122. }
  75123. };
  75124. this._onFullscreenChange = function () {
  75125. if (document.fullscreen !== undefined) {
  75126. _this._fullscreenVRpresenting = document.fullscreen;
  75127. }
  75128. else if (document.mozFullScreen !== undefined) {
  75129. _this._fullscreenVRpresenting = document.mozFullScreen;
  75130. }
  75131. else if (document.webkitIsFullScreen !== undefined) {
  75132. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  75133. }
  75134. else if (document.msIsFullScreen !== undefined) {
  75135. _this._fullscreenVRpresenting = document.msIsFullScreen;
  75136. }
  75137. if (!_this._fullscreenVRpresenting && _this._canvas) {
  75138. _this.exitVR();
  75139. if (!_this._useCustomVRButton) {
  75140. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  75141. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  75142. }
  75143. }
  75144. };
  75145. this.beforeRender = function () {
  75146. _this._castRayAndSelectObject();
  75147. };
  75148. this._onNewGamepadConnected = function (gamepad) {
  75149. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75150. if (gamepad.leftStick) {
  75151. gamepad.onleftstickchanged(function (stickValues) {
  75152. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  75153. // Listening to classic/xbox gamepad only if no VR controller is active
  75154. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  75155. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  75156. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  75157. _this._checkTeleportWithRay(stickValues);
  75158. _this._checkTeleportBackwards(stickValues);
  75159. }
  75160. }
  75161. });
  75162. }
  75163. if (gamepad.rightStick) {
  75164. gamepad.onrightstickchanged(function (stickValues) {
  75165. if (_this._teleportationInitialized) {
  75166. _this._checkRotate(stickValues);
  75167. }
  75168. });
  75169. }
  75170. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  75171. gamepad.onbuttondown(function (buttonPressed) {
  75172. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75173. _this._selectionPointerDown();
  75174. }
  75175. });
  75176. gamepad.onbuttonup(function (buttonPressed) {
  75177. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75178. _this._selectionPointerUp();
  75179. }
  75180. });
  75181. }
  75182. }
  75183. else {
  75184. var webVRController = gamepad;
  75185. _this._tryEnableInteractionOnController(webVRController);
  75186. }
  75187. };
  75188. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  75189. this._tryEnableInteractionOnController = function (webVRController) {
  75190. if (webVRController.hand === "left") {
  75191. _this._leftControllerReady = true;
  75192. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  75193. _this._enableInteractionOnController(webVRController);
  75194. }
  75195. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  75196. _this._enableTeleportationOnController(webVRController);
  75197. }
  75198. }
  75199. if (webVRController.hand === "right") {
  75200. _this._rightControllerReady = true;
  75201. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  75202. _this._enableInteractionOnController(webVRController);
  75203. }
  75204. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  75205. _this._enableTeleportationOnController(webVRController);
  75206. }
  75207. }
  75208. };
  75209. this._onNewGamepadDisconnected = function (gamepad) {
  75210. if (gamepad instanceof BABYLON.WebVRController) {
  75211. if (gamepad.hand === "left") {
  75212. _this._interactionsEnabledOnLeftController = false;
  75213. _this._teleportationEnabledOnLeftController = false;
  75214. _this._leftControllerReady = false;
  75215. if (_this._leftLaserPointer) {
  75216. _this._leftLaserPointer.dispose();
  75217. }
  75218. }
  75219. if (gamepad.hand === "right") {
  75220. _this._interactionsEnabledOnRightController = false;
  75221. _this._teleportationEnabledOnRightController = false;
  75222. _this._rightControllerReady = false;
  75223. if (_this._rightLaserPointer) {
  75224. _this._rightLaserPointer.dispose();
  75225. }
  75226. }
  75227. }
  75228. };
  75229. this._workingVector = BABYLON.Vector3.Zero();
  75230. this._workingQuaternion = BABYLON.Quaternion.Identity();
  75231. this._workingMatrix = BABYLON.Matrix.Identity();
  75232. this._scene = scene;
  75233. this._canvas = scene.getEngine().getRenderingCanvas();
  75234. // Parse options
  75235. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  75236. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  75237. }
  75238. if (webVROptions.createDeviceOrientationCamera === undefined) {
  75239. webVROptions.createDeviceOrientationCamera = true;
  75240. }
  75241. if (webVROptions.defaultHeight === undefined) {
  75242. webVROptions.defaultHeight = 1.7;
  75243. }
  75244. if (webVROptions.useCustomVRButton) {
  75245. this._useCustomVRButton = true;
  75246. if (webVROptions.customVRButton) {
  75247. this._btnVR = webVROptions.customVRButton;
  75248. }
  75249. }
  75250. if (webVROptions.rayLength) {
  75251. this._rayLength = webVROptions.rayLength;
  75252. }
  75253. this._defaultHeight = webVROptions.defaultHeight;
  75254. // Set position
  75255. if (this._scene.activeCamera) {
  75256. this._position = this._scene.activeCamera.position.clone();
  75257. }
  75258. else {
  75259. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  75260. }
  75261. // Set non-vr camera
  75262. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  75263. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  75264. // Copy data from existing camera
  75265. if (this._scene.activeCamera) {
  75266. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  75267. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  75268. // Set rotation from previous camera
  75269. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  75270. var targetCamera = this._scene.activeCamera;
  75271. if (targetCamera.rotationQuaternion) {
  75272. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  75273. }
  75274. else {
  75275. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  75276. }
  75277. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  75278. }
  75279. }
  75280. this._scene.activeCamera = this._deviceOrientationCamera;
  75281. if (this._canvas) {
  75282. this._scene.activeCamera.attachControl(this._canvas);
  75283. }
  75284. }
  75285. else {
  75286. this._existingCamera = this._scene.activeCamera;
  75287. }
  75288. // Create VR cameras
  75289. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75290. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75291. }
  75292. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75293. this._webVRCamera.useStandingMatrix();
  75294. // Create default button
  75295. if (!this._useCustomVRButton) {
  75296. this._btnVR = document.createElement("BUTTON");
  75297. this._btnVR.className = "babylonVRicon";
  75298. this._btnVR.id = "babylonVRiconbtn";
  75299. this._btnVR.title = "Click to switch to VR";
  75300. 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) }";
  75301. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75302. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75303. // css += ".babylonVRicon.vrdisplaysupported { }";
  75304. // css += ".babylonVRicon.vrdisplayready { }";
  75305. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75306. var style = document.createElement('style');
  75307. style.appendChild(document.createTextNode(css));
  75308. document.getElementsByTagName('head')[0].appendChild(style);
  75309. this.moveButtonToBottomRight();
  75310. }
  75311. // VR button click event
  75312. if (this._btnVR) {
  75313. this._btnVR.addEventListener("click", function () {
  75314. if (!_this.isInVRMode) {
  75315. _this.enterVR();
  75316. }
  75317. else {
  75318. _this.exitVR();
  75319. }
  75320. });
  75321. }
  75322. // Window events
  75323. window.addEventListener("resize", this._onResize);
  75324. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75325. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75326. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75327. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75328. // Display vr button when headset is connected
  75329. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75330. this.displayVRButton();
  75331. }
  75332. else {
  75333. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75334. if (e.vrDisplay) {
  75335. _this.displayVRButton();
  75336. }
  75337. });
  75338. }
  75339. // Exiting VR mode using 'ESC' key on desktop
  75340. this._onKeyDown = function (event) {
  75341. if (event.keyCode === 27 && _this.isInVRMode) {
  75342. _this.exitVR();
  75343. }
  75344. };
  75345. document.addEventListener("keydown", this._onKeyDown);
  75346. // Exiting VR mode double tapping the touch screen
  75347. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75348. if (_this.isInVRMode) {
  75349. _this.exitVR();
  75350. if (_this._fullscreenVRpresenting) {
  75351. _this._scene.getEngine().switchFullscreen(true);
  75352. }
  75353. }
  75354. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75355. // Listen for WebVR display changes
  75356. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75357. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75358. this._onVRRequestPresentStart = function () {
  75359. _this._webVRrequesting = true;
  75360. _this.updateButtonVisibility();
  75361. };
  75362. this._onVRRequestPresentComplete = function (success) {
  75363. _this._webVRrequesting = false;
  75364. _this.updateButtonVisibility();
  75365. };
  75366. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75367. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75368. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75369. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75370. scene.onDisposeObservable.add(function () {
  75371. _this.dispose();
  75372. });
  75373. // Gamepad connection events
  75374. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75375. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75376. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75377. this.updateButtonVisibility();
  75378. //create easing functions
  75379. this._circleEase = new BABYLON.CircleEase();
  75380. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75381. }
  75382. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75383. /** Return this.onEnteringVRObservable
  75384. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75385. */
  75386. get: function () {
  75387. return this.onEnteringVRObservable;
  75388. },
  75389. enumerable: true,
  75390. configurable: true
  75391. });
  75392. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75393. /** Return this.onExitingVRObservable
  75394. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75395. */
  75396. get: function () {
  75397. return this.onExitingVRObservable;
  75398. },
  75399. enumerable: true,
  75400. configurable: true
  75401. });
  75402. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75403. /** Return this.onControllerMeshLoadedObservable
  75404. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75405. */
  75406. get: function () {
  75407. return this.onControllerMeshLoadedObservable;
  75408. },
  75409. enumerable: true,
  75410. configurable: true
  75411. });
  75412. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  75413. /**
  75414. * The mesh used to display where the user is going to teleport.
  75415. */
  75416. get: function () {
  75417. return this._teleportationTarget;
  75418. },
  75419. /**
  75420. * Sets the mesh to be used to display where the user is going to teleport.
  75421. */
  75422. set: function (value) {
  75423. if (value) {
  75424. value.name = "teleportationTarget";
  75425. this._isDefaultTeleportationTarget = false;
  75426. this._teleportationTarget = value;
  75427. }
  75428. },
  75429. enumerable: true,
  75430. configurable: true
  75431. });
  75432. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  75433. /**
  75434. * If the ray of the gaze should be displayed.
  75435. */
  75436. get: function () {
  75437. return this._displayGaze;
  75438. },
  75439. /**
  75440. * Sets if the ray of the gaze should be displayed.
  75441. */
  75442. set: function (value) {
  75443. this._displayGaze = value;
  75444. if (!value) {
  75445. this._gazeTracker.isVisible = false;
  75446. }
  75447. },
  75448. enumerable: true,
  75449. configurable: true
  75450. });
  75451. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  75452. /**
  75453. * If the ray of the LaserPointer should be displayed.
  75454. */
  75455. get: function () {
  75456. return this._displayLaserPointer;
  75457. },
  75458. /**
  75459. * Sets if the ray of the LaserPointer should be displayed.
  75460. */
  75461. set: function (value) {
  75462. this._displayLaserPointer = value;
  75463. if (!value) {
  75464. if (this._rightLaserPointer) {
  75465. this._rightLaserPointer.isVisible = false;
  75466. }
  75467. if (this._leftLaserPointer) {
  75468. this._leftLaserPointer.isVisible = false;
  75469. }
  75470. }
  75471. else {
  75472. if (this._rightLaserPointer) {
  75473. this._rightLaserPointer.isVisible = true;
  75474. }
  75475. else if (this._leftLaserPointer) {
  75476. this._leftLaserPointer.isVisible = true;
  75477. }
  75478. }
  75479. },
  75480. enumerable: true,
  75481. configurable: true
  75482. });
  75483. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  75484. /**
  75485. * The deviceOrientationCamera used as the camera when not in VR.
  75486. */
  75487. get: function () {
  75488. return this._deviceOrientationCamera;
  75489. },
  75490. enumerable: true,
  75491. configurable: true
  75492. });
  75493. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  75494. /**
  75495. * Based on the current WebVR support, returns the current VR camera used.
  75496. */
  75497. get: function () {
  75498. if (this._webVRready) {
  75499. return this._webVRCamera;
  75500. }
  75501. else {
  75502. return this._scene.activeCamera;
  75503. }
  75504. },
  75505. enumerable: true,
  75506. configurable: true
  75507. });
  75508. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  75509. /**
  75510. * The webVRCamera which is used when in VR.
  75511. */
  75512. get: function () {
  75513. return this._webVRCamera;
  75514. },
  75515. enumerable: true,
  75516. configurable: true
  75517. });
  75518. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  75519. /**
  75520. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  75521. */
  75522. get: function () {
  75523. return this._vrDeviceOrientationCamera;
  75524. },
  75525. enumerable: true,
  75526. configurable: true
  75527. });
  75528. // Raised when one of the controller has loaded successfully its associated default mesh
  75529. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  75530. this._tryEnableInteractionOnController(webVRController);
  75531. try {
  75532. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  75533. }
  75534. catch (err) {
  75535. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  75536. }
  75537. };
  75538. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  75539. /**
  75540. * Gets a value indicating if we are currently in VR mode.
  75541. */
  75542. get: function () {
  75543. return this._webVRpresenting || this._fullscreenVRpresenting;
  75544. },
  75545. enumerable: true,
  75546. configurable: true
  75547. });
  75548. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  75549. var vrDisplay = this._scene.getEngine().getVRDevice();
  75550. if (vrDisplay) {
  75551. var wasPresenting = this._webVRpresenting;
  75552. // A VR display is connected
  75553. this._webVRpresenting = vrDisplay.isPresenting;
  75554. if (wasPresenting && !this._webVRpresenting)
  75555. this.exitVR();
  75556. }
  75557. else {
  75558. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  75559. }
  75560. this.updateButtonVisibility();
  75561. };
  75562. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  75563. this._webVRsupported = eventArgs.vrSupported;
  75564. this._webVRready = !!eventArgs.vrDisplay;
  75565. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  75566. this.updateButtonVisibility();
  75567. };
  75568. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  75569. if (this._canvas && !this._useCustomVRButton) {
  75570. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  75571. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  75572. }
  75573. };
  75574. VRExperienceHelper.prototype.displayVRButton = function () {
  75575. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  75576. document.body.appendChild(this._btnVR);
  75577. this._btnVRDisplayed = true;
  75578. }
  75579. };
  75580. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  75581. if (!this._btnVR || this._useCustomVRButton) {
  75582. return;
  75583. }
  75584. this._btnVR.className = "babylonVRicon";
  75585. if (this.isInVRMode) {
  75586. this._btnVR.className += " vrdisplaypresenting";
  75587. }
  75588. else {
  75589. if (this._webVRready)
  75590. this._btnVR.className += " vrdisplayready";
  75591. if (this._webVRsupported)
  75592. this._btnVR.className += " vrdisplaysupported";
  75593. if (this._webVRrequesting)
  75594. this._btnVR.className += " vrdisplayrequesting";
  75595. }
  75596. };
  75597. /**
  75598. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  75599. * Otherwise, will use the fullscreen API.
  75600. */
  75601. VRExperienceHelper.prototype.enterVR = function () {
  75602. if (this.onEnteringVRObservable) {
  75603. try {
  75604. this.onEnteringVRObservable.notifyObservers(this);
  75605. }
  75606. catch (err) {
  75607. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  75608. }
  75609. }
  75610. if (this._scene.activeCamera) {
  75611. this._position = this._scene.activeCamera.position.clone();
  75612. // make sure that we return to the last active camera
  75613. this._existingCamera = this._scene.activeCamera;
  75614. }
  75615. if (this._webVRrequesting)
  75616. return;
  75617. // If WebVR is supported and a headset is connected
  75618. if (this._webVRready) {
  75619. if (!this._webVRpresenting) {
  75620. this._webVRCamera.position = this._position;
  75621. this._scene.activeCamera = this._webVRCamera;
  75622. }
  75623. }
  75624. else if (this._vrDeviceOrientationCamera) {
  75625. this._vrDeviceOrientationCamera.position = this._position;
  75626. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  75627. this._scene.getEngine().switchFullscreen(true);
  75628. this.updateButtonVisibility();
  75629. }
  75630. if (this._scene.activeCamera && this._canvas) {
  75631. this._scene.activeCamera.attachControl(this._canvas);
  75632. }
  75633. if (this._interactionsEnabled) {
  75634. this._scene.registerBeforeRender(this.beforeRender);
  75635. }
  75636. };
  75637. /**
  75638. * Attempt to exit VR, or fullscreen.
  75639. */
  75640. VRExperienceHelper.prototype.exitVR = function () {
  75641. if (this.onExitingVRObservable) {
  75642. try {
  75643. this.onExitingVRObservable.notifyObservers(this);
  75644. }
  75645. catch (err) {
  75646. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  75647. }
  75648. }
  75649. if (this._webVRpresenting) {
  75650. this._scene.getEngine().disableVR();
  75651. }
  75652. if (this._scene.activeCamera) {
  75653. this._position = this._scene.activeCamera.position.clone();
  75654. }
  75655. if (this._deviceOrientationCamera) {
  75656. this._deviceOrientationCamera.position = this._position;
  75657. this._scene.activeCamera = this._deviceOrientationCamera;
  75658. if (this._canvas) {
  75659. this._scene.activeCamera.attachControl(this._canvas);
  75660. }
  75661. }
  75662. else if (this._existingCamera) {
  75663. this._existingCamera.position = this._position;
  75664. this._scene.activeCamera = this._existingCamera;
  75665. }
  75666. this.updateButtonVisibility();
  75667. if (this._interactionsEnabled) {
  75668. this._scene.unregisterBeforeRender(this.beforeRender);
  75669. }
  75670. };
  75671. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  75672. /**
  75673. * The position of the vr experience helper.
  75674. */
  75675. get: function () {
  75676. return this._position;
  75677. },
  75678. /**
  75679. * Sets the position of the vr experience helper.
  75680. */
  75681. set: function (value) {
  75682. this._position = value;
  75683. if (this._scene.activeCamera) {
  75684. this._scene.activeCamera.position = value;
  75685. }
  75686. },
  75687. enumerable: true,
  75688. configurable: true
  75689. });
  75690. /**
  75691. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  75692. */
  75693. VRExperienceHelper.prototype.enableInteractions = function () {
  75694. var _this = this;
  75695. if (!this._interactionsEnabled) {
  75696. this._interactionsRequested = true;
  75697. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75698. this._enableInteractionOnController(this._webVRCamera.leftController);
  75699. }
  75700. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75701. this._enableInteractionOnController(this._webVRCamera.rightController);
  75702. }
  75703. this._createGazeTracker();
  75704. this.raySelectionPredicate = function (mesh) {
  75705. return mesh.isVisible;
  75706. };
  75707. this.meshSelectionPredicate = function (mesh) {
  75708. return true;
  75709. };
  75710. this._raySelectionPredicate = function (mesh) {
  75711. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  75712. && mesh.name.indexOf("teleportationTarget") === -1
  75713. && mesh.name.indexOf("torusTeleportation") === -1
  75714. && mesh.name.indexOf("laserPointer") === -1)) {
  75715. return _this.raySelectionPredicate(mesh);
  75716. }
  75717. return false;
  75718. };
  75719. this._interactionsEnabled = true;
  75720. }
  75721. };
  75722. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  75723. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  75724. if (this._floorMeshesCollection[i].id === mesh.id) {
  75725. return true;
  75726. }
  75727. }
  75728. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  75729. return true;
  75730. }
  75731. return false;
  75732. };
  75733. /**
  75734. * Adds a floor mesh to be used for teleportation.
  75735. * @param floorMesh the mesh to be used for teleportation.
  75736. */
  75737. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  75738. if (!this._floorMeshesCollection) {
  75739. return;
  75740. }
  75741. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  75742. return;
  75743. }
  75744. this._floorMeshesCollection.push(floorMesh);
  75745. };
  75746. /**
  75747. * Removes a floor mesh from being used for teleportation.
  75748. * @param floorMesh the mesh to be removed.
  75749. */
  75750. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  75751. if (!this._floorMeshesCollection) {
  75752. return;
  75753. }
  75754. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  75755. if (meshIndex !== -1) {
  75756. this._floorMeshesCollection.splice(meshIndex, 1);
  75757. }
  75758. };
  75759. /**
  75760. * Enables interactions and teleportation using the VR controllers and gaze.
  75761. * @param vrTeleportationOptions options to modify teleportation behavior.
  75762. */
  75763. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  75764. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  75765. if (!this._teleportationInitialized) {
  75766. this._teleportationRequested = true;
  75767. this.enableInteractions();
  75768. if (vrTeleportationOptions.floorMeshName) {
  75769. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  75770. }
  75771. if (vrTeleportationOptions.floorMeshes) {
  75772. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  75773. }
  75774. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75775. this._enableTeleportationOnController(this._webVRCamera.leftController);
  75776. }
  75777. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75778. this._enableTeleportationOnController(this._webVRCamera.rightController);
  75779. }
  75780. // Creates an image processing post process for the vignette not relying
  75781. // on the main scene configuration for image processing to reduce setup and spaces
  75782. // (gamma/linear) conflicts.
  75783. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  75784. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  75785. imageProcessingConfiguration.vignetteEnabled = true;
  75786. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  75787. this._webVRCamera.detachPostProcess(this._postProcessMove);
  75788. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  75789. this._teleportationInitialized = true;
  75790. if (this._isDefaultTeleportationTarget) {
  75791. this._createTeleportationCircles();
  75792. }
  75793. }
  75794. };
  75795. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  75796. var _this = this;
  75797. var controllerMesh = webVRController.mesh;
  75798. if (controllerMesh) {
  75799. var makeNotPick = function (root) {
  75800. root.name += " laserPointer";
  75801. root.getChildMeshes().forEach(function (c) {
  75802. makeNotPick(c);
  75803. });
  75804. };
  75805. makeNotPick(controllerMesh);
  75806. var childMeshes = controllerMesh.getChildMeshes();
  75807. for (var i = 0; i < childMeshes.length; i++) {
  75808. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  75809. controllerMesh = childMeshes[i];
  75810. break;
  75811. }
  75812. }
  75813. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  75814. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  75815. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  75816. laserPointerMaterial.alpha = 0.6;
  75817. laserPointer.material = laserPointerMaterial;
  75818. laserPointer.rotation.x = Math.PI / 2;
  75819. laserPointer.parent = controllerMesh;
  75820. laserPointer.position.z = -0.5;
  75821. laserPointer.isVisible = false;
  75822. if (webVRController.hand === "left") {
  75823. this._leftLaserPointer = laserPointer;
  75824. this._interactionsEnabledOnLeftController = true;
  75825. if (!this._rightLaserPointer) {
  75826. this._leftLaserPointer.isVisible = true;
  75827. }
  75828. }
  75829. else {
  75830. this._rightLaserPointer = laserPointer;
  75831. this._interactionsEnabledOnRightController = true;
  75832. if (!this._leftLaserPointer) {
  75833. this._rightLaserPointer.isVisible = true;
  75834. }
  75835. }
  75836. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  75837. // Enabling / disabling laserPointer
  75838. if (_this._displayLaserPointer && stateObject.value === 1) {
  75839. laserPointer.isVisible = !laserPointer.isVisible;
  75840. // Laser pointer can only be active on left or right, not both at the same time
  75841. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  75842. _this._rightLaserPointer.isVisible = false;
  75843. }
  75844. else if (_this._leftLaserPointer) {
  75845. _this._leftLaserPointer.isVisible = false;
  75846. }
  75847. }
  75848. });
  75849. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  75850. if (!_this._pointerDownOnMeshAsked) {
  75851. if (stateObject.value > _this._padSensibilityUp) {
  75852. _this._selectionPointerDown();
  75853. }
  75854. }
  75855. else if (stateObject.value < _this._padSensibilityDown) {
  75856. _this._selectionPointerUp();
  75857. }
  75858. });
  75859. }
  75860. };
  75861. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  75862. if (webVRController === void 0) { webVRController = null; }
  75863. if (!this._teleportationRequestInitiated) {
  75864. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  75865. if (webVRController) {
  75866. // If laser pointer wasn't enabled yet
  75867. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  75868. this._leftLaserPointer.isVisible = true;
  75869. if (this._rightLaserPointer) {
  75870. this._rightLaserPointer.isVisible = false;
  75871. }
  75872. }
  75873. else if (this._displayLaserPointer && this._rightLaserPointer) {
  75874. this._rightLaserPointer.isVisible = true;
  75875. if (this._leftLaserPointer) {
  75876. this._leftLaserPointer.isVisible = false;
  75877. }
  75878. }
  75879. }
  75880. this._teleportationRequestInitiated = true;
  75881. }
  75882. }
  75883. else {
  75884. // Listening to the proper controller values changes to confirm teleportation
  75885. if (webVRController == null
  75886. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  75887. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  75888. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  75889. if (this._teleportationAllowed) {
  75890. this._teleportationAllowed = false;
  75891. this._teleportCamera();
  75892. }
  75893. this._teleportationRequestInitiated = false;
  75894. }
  75895. }
  75896. }
  75897. };
  75898. VRExperienceHelper.prototype._selectionPointerDown = function () {
  75899. this._pointerDownOnMeshAsked = true;
  75900. if (this._currentMeshSelected && this._currentHit) {
  75901. this._scene.simulatePointerDown(this._currentHit);
  75902. }
  75903. };
  75904. VRExperienceHelper.prototype._selectionPointerUp = function () {
  75905. if (this._currentMeshSelected && this._currentHit) {
  75906. this._scene.simulatePointerUp(this._currentHit);
  75907. }
  75908. this._pointerDownOnMeshAsked = false;
  75909. };
  75910. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  75911. // Only rotate when user is not currently selecting a teleportation location
  75912. if (this._teleportationRequestInitiated) {
  75913. return;
  75914. }
  75915. if (!this._rotationLeftAsked) {
  75916. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  75917. this._rotationLeftAsked = true;
  75918. if (this._rotationAllowed) {
  75919. this._rotateCamera(false);
  75920. }
  75921. }
  75922. }
  75923. else {
  75924. if (stateObject.x > -this._padSensibilityDown) {
  75925. this._rotationLeftAsked = false;
  75926. }
  75927. }
  75928. if (!this._rotationRightAsked) {
  75929. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  75930. this._rotationRightAsked = true;
  75931. if (this._rotationAllowed) {
  75932. this._rotateCamera(true);
  75933. }
  75934. }
  75935. }
  75936. else {
  75937. if (stateObject.x < this._padSensibilityDown) {
  75938. this._rotationRightAsked = false;
  75939. }
  75940. }
  75941. };
  75942. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  75943. // Only teleport backwards when user is not currently selecting a teleportation location
  75944. if (this._teleportationRequestInitiated) {
  75945. return;
  75946. }
  75947. // Teleport backwards
  75948. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  75949. if (!this._teleportationBackRequestInitiated) {
  75950. if (!this.currentVRCamera) {
  75951. return;
  75952. }
  75953. // Get rotation and position of the current camera
  75954. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  75955. var position = this.currentVRCamera.position;
  75956. // If the camera has device position, use that instead
  75957. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  75958. rotation = this.currentVRCamera.deviceRotationQuaternion;
  75959. position = this.currentVRCamera.devicePosition;
  75960. }
  75961. // Get matrix with only the y rotation of the device rotation
  75962. rotation.toEulerAnglesToRef(this._workingVector);
  75963. this._workingVector.z = 0;
  75964. this._workingVector.x = 0;
  75965. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  75966. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  75967. // Rotate backwards ray by device rotation to cast at the ground behind the user
  75968. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  75969. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  75970. var ray = new BABYLON.Ray(position, this._workingVector);
  75971. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  75972. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  75973. this._teleportCamera(hit.pickedPoint);
  75974. }
  75975. this._teleportationBackRequestInitiated = true;
  75976. }
  75977. }
  75978. else {
  75979. this._teleportationBackRequestInitiated = false;
  75980. }
  75981. };
  75982. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  75983. var _this = this;
  75984. var controllerMesh = webVRController.mesh;
  75985. if (controllerMesh) {
  75986. if (webVRController.hand === "left") {
  75987. if (!this._interactionsEnabledOnLeftController) {
  75988. this._enableInteractionOnController(webVRController);
  75989. }
  75990. this._teleportationEnabledOnLeftController = true;
  75991. }
  75992. else {
  75993. if (!this._interactionsEnabledOnRightController) {
  75994. this._enableInteractionOnController(webVRController);
  75995. }
  75996. this._teleportationEnabledOnRightController = true;
  75997. }
  75998. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75999. this._dpadPressed = false;
  76000. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  76001. _this._dpadPressed = stateObject.pressed;
  76002. if (!_this._dpadPressed) {
  76003. _this._rotationLeftAsked = false;
  76004. _this._rotationRightAsked = false;
  76005. _this._teleportationBackRequestInitiated = false;
  76006. }
  76007. });
  76008. }
  76009. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  76010. if (_this.teleportationEnabled) {
  76011. _this._checkTeleportBackwards(stateObject);
  76012. _this._checkTeleportWithRay(stateObject, webVRController);
  76013. }
  76014. _this._checkRotate(stateObject);
  76015. });
  76016. }
  76017. };
  76018. // Gaze support used to point to teleport or to interact with an object
  76019. VRExperienceHelper.prototype._createGazeTracker = function () {
  76020. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  76021. this._gazeTracker.bakeCurrentTransformIntoVertices();
  76022. this._gazeTracker.isPickable = false;
  76023. this._gazeTracker.isVisible = false;
  76024. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  76025. targetMat.specularColor = BABYLON.Color3.Black();
  76026. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76027. targetMat.backFaceCulling = false;
  76028. this._gazeTracker.material = targetMat;
  76029. };
  76030. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  76031. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  76032. this._teleportationTarget.isPickable = false;
  76033. var length = 512;
  76034. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  76035. dynamicTexture.hasAlpha = true;
  76036. var context = dynamicTexture.getContext();
  76037. var centerX = length / 2;
  76038. var centerY = length / 2;
  76039. var radius = 200;
  76040. context.beginPath();
  76041. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  76042. context.fillStyle = this._teleportationFillColor;
  76043. context.fill();
  76044. context.lineWidth = 10;
  76045. context.strokeStyle = this._teleportationBorderColor;
  76046. context.stroke();
  76047. context.closePath();
  76048. dynamicTexture.update();
  76049. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  76050. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  76051. this._teleportationTarget.material = teleportationCircleMaterial;
  76052. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  76053. torus.isPickable = false;
  76054. torus.parent = this._teleportationTarget;
  76055. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76056. var keys = [];
  76057. keys.push({
  76058. frame: 0,
  76059. value: 0
  76060. });
  76061. keys.push({
  76062. frame: 30,
  76063. value: 0.4
  76064. });
  76065. keys.push({
  76066. frame: 60,
  76067. value: 0
  76068. });
  76069. animationInnerCircle.setKeys(keys);
  76070. var easingFunction = new BABYLON.SineEase();
  76071. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76072. animationInnerCircle.setEasingFunction(easingFunction);
  76073. torus.animations = [];
  76074. torus.animations.push(animationInnerCircle);
  76075. this._scene.beginAnimation(torus, 0, 60, true);
  76076. this._hideTeleportationTarget();
  76077. };
  76078. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  76079. if (this._teleportationInitialized) {
  76080. this._teleportationTarget.isVisible = true;
  76081. if (this._isDefaultTeleportationTarget) {
  76082. this._teleportationTarget.getChildren()[0].isVisible = true;
  76083. }
  76084. }
  76085. };
  76086. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  76087. if (this._teleportationInitialized) {
  76088. this._teleportationTarget.isVisible = false;
  76089. if (this._isDefaultTeleportationTarget) {
  76090. this._teleportationTarget.getChildren()[0].isVisible = false;
  76091. }
  76092. }
  76093. };
  76094. VRExperienceHelper.prototype._rotateCamera = function (right) {
  76095. var _this = this;
  76096. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76097. return;
  76098. }
  76099. if (right) {
  76100. this._rotationAngle++;
  76101. }
  76102. else {
  76103. this._rotationAngle--;
  76104. }
  76105. this.currentVRCamera.animations = [];
  76106. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  76107. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76108. var animationRotationKeys = [];
  76109. animationRotationKeys.push({
  76110. frame: 0,
  76111. value: this.currentVRCamera.rotationQuaternion
  76112. });
  76113. animationRotationKeys.push({
  76114. frame: 6,
  76115. value: target
  76116. });
  76117. animationRotation.setKeys(animationRotationKeys);
  76118. animationRotation.setEasingFunction(this._circleEase);
  76119. this.currentVRCamera.animations.push(animationRotation);
  76120. this._postProcessMove.animations = [];
  76121. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76122. var vignetteWeightKeys = [];
  76123. vignetteWeightKeys.push({
  76124. frame: 0,
  76125. value: 0
  76126. });
  76127. vignetteWeightKeys.push({
  76128. frame: 3,
  76129. value: 4
  76130. });
  76131. vignetteWeightKeys.push({
  76132. frame: 6,
  76133. value: 0
  76134. });
  76135. animationPP.setKeys(vignetteWeightKeys);
  76136. animationPP.setEasingFunction(this._circleEase);
  76137. this._postProcessMove.animations.push(animationPP);
  76138. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76139. var vignetteStretchKeys = [];
  76140. vignetteStretchKeys.push({
  76141. frame: 0,
  76142. value: 0
  76143. });
  76144. vignetteStretchKeys.push({
  76145. frame: 3,
  76146. value: 10
  76147. });
  76148. vignetteStretchKeys.push({
  76149. frame: 6,
  76150. value: 0
  76151. });
  76152. animationPP2.setKeys(vignetteStretchKeys);
  76153. animationPP2.setEasingFunction(this._circleEase);
  76154. this._postProcessMove.animations.push(animationPP2);
  76155. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76156. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76157. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76158. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  76159. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76160. });
  76161. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  76162. };
  76163. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  76164. if (hit.pickedPoint) {
  76165. this._teleportationAllowed = true;
  76166. if (this._teleportationRequestInitiated) {
  76167. this._displayTeleportationTarget();
  76168. }
  76169. else {
  76170. this._hideTeleportationTarget();
  76171. }
  76172. this._haloCenter.copyFrom(hit.pickedPoint);
  76173. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  76174. var pickNormal = hit.getNormal(true, false);
  76175. if (pickNormal) {
  76176. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76177. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76178. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  76179. }
  76180. this._teleportationTarget.position.y += 0.1;
  76181. }
  76182. };
  76183. VRExperienceHelper.prototype._teleportCamera = function (location) {
  76184. var _this = this;
  76185. if (location === void 0) { location = null; }
  76186. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76187. return;
  76188. }
  76189. if (!location) {
  76190. location = this._haloCenter;
  76191. }
  76192. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  76193. // offset of the headset from the anchor.
  76194. if (this.webVRCamera.leftCamera) {
  76195. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  76196. this._workingVector.subtractInPlace(this.webVRCamera.position);
  76197. location.subtractToRef(this._workingVector, this._workingVector);
  76198. }
  76199. else {
  76200. this._workingVector.copyFrom(location);
  76201. }
  76202. // Add height to account for user's height offset
  76203. if (this.isInVRMode) {
  76204. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  76205. }
  76206. else {
  76207. this._workingVector.y += this._defaultHeight;
  76208. }
  76209. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  76210. // Create animation from the camera's position to the new location
  76211. this.currentVRCamera.animations = [];
  76212. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76213. var animationCameraTeleportationKeys = [{
  76214. frame: 0,
  76215. value: this.currentVRCamera.position
  76216. },
  76217. {
  76218. frame: 11,
  76219. value: this._workingVector
  76220. }
  76221. ];
  76222. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  76223. animationCameraTeleportation.setEasingFunction(this._circleEase);
  76224. this.currentVRCamera.animations.push(animationCameraTeleportation);
  76225. this._postProcessMove.animations = [];
  76226. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76227. var vignetteWeightKeys = [];
  76228. vignetteWeightKeys.push({
  76229. frame: 0,
  76230. value: 0
  76231. });
  76232. vignetteWeightKeys.push({
  76233. frame: 5,
  76234. value: 8
  76235. });
  76236. vignetteWeightKeys.push({
  76237. frame: 11,
  76238. value: 0
  76239. });
  76240. animationPP.setKeys(vignetteWeightKeys);
  76241. this._postProcessMove.animations.push(animationPP);
  76242. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76243. var vignetteStretchKeys = [];
  76244. vignetteStretchKeys.push({
  76245. frame: 0,
  76246. value: 0
  76247. });
  76248. vignetteStretchKeys.push({
  76249. frame: 5,
  76250. value: 10
  76251. });
  76252. vignetteStretchKeys.push({
  76253. frame: 11,
  76254. value: 0
  76255. });
  76256. animationPP2.setKeys(vignetteStretchKeys);
  76257. this._postProcessMove.animations.push(animationPP2);
  76258. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76259. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76260. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76261. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  76262. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76263. });
  76264. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  76265. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  76266. });
  76267. };
  76268. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  76269. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76270. return;
  76271. }
  76272. var ray;
  76273. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  76274. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  76275. }
  76276. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  76277. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  76278. }
  76279. else {
  76280. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  76281. }
  76282. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76283. // Moving the gazeTracker on the mesh face targetted
  76284. if (hit && hit.pickedPoint) {
  76285. if (this._displayGaze) {
  76286. var multiplier = 1;
  76287. this._gazeTracker.isVisible = true;
  76288. if (this._isActionableMesh) {
  76289. multiplier = 3;
  76290. }
  76291. this._gazeTracker.scaling.x = hit.distance * multiplier;
  76292. this._gazeTracker.scaling.y = hit.distance * multiplier;
  76293. this._gazeTracker.scaling.z = hit.distance * multiplier;
  76294. var pickNormal = hit.getNormal();
  76295. // To avoid z-fighting
  76296. var deltaFighting = 0.002;
  76297. if (pickNormal) {
  76298. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76299. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76300. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  76301. }
  76302. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  76303. if (this._gazeTracker.position.x < 0) {
  76304. this._gazeTracker.position.x += deltaFighting;
  76305. }
  76306. else {
  76307. this._gazeTracker.position.x -= deltaFighting;
  76308. }
  76309. if (this._gazeTracker.position.y < 0) {
  76310. this._gazeTracker.position.y += deltaFighting;
  76311. }
  76312. else {
  76313. this._gazeTracker.position.y -= deltaFighting;
  76314. }
  76315. if (this._gazeTracker.position.z < 0) {
  76316. this._gazeTracker.position.z += deltaFighting;
  76317. }
  76318. else {
  76319. this._gazeTracker.position.z -= deltaFighting;
  76320. }
  76321. }
  76322. // Changing the size of the laser pointer based on the distance from the targetted point
  76323. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  76324. this._rightLaserPointer.scaling.y = hit.distance;
  76325. this._rightLaserPointer.position.z = -hit.distance / 2;
  76326. }
  76327. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  76328. this._leftLaserPointer.scaling.y = hit.distance;
  76329. this._leftLaserPointer.position.z = -hit.distance / 2;
  76330. }
  76331. }
  76332. else {
  76333. this._gazeTracker.isVisible = false;
  76334. }
  76335. if (hit && hit.pickedMesh) {
  76336. this._currentHit = hit;
  76337. if (this._pointerDownOnMeshAsked) {
  76338. this._scene.simulatePointerMove(this._currentHit);
  76339. }
  76340. // The object selected is the floor, we're in a teleportation scenario
  76341. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76342. // Moving the teleportation area to this targetted point
  76343. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76344. if (this._currentMeshSelected &&
  76345. !this._isTeleportationFloor(this._currentMeshSelected)) {
  76346. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76347. }
  76348. this._currentMeshSelected = null;
  76349. this._moveTeleportationSelectorTo(hit);
  76350. return;
  76351. }
  76352. // If not, we're in a selection scenario
  76353. this._hideTeleportationTarget();
  76354. this._teleportationAllowed = false;
  76355. if (hit.pickedMesh !== this._currentMeshSelected) {
  76356. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76357. this.onNewMeshPicked.notifyObservers(hit);
  76358. this._currentMeshSelected = hit.pickedMesh;
  76359. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76360. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76361. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76362. this._isActionableMesh = true;
  76363. }
  76364. else {
  76365. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76366. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76367. this._isActionableMesh = false;
  76368. }
  76369. try {
  76370. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76371. }
  76372. catch (err) {
  76373. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76374. }
  76375. }
  76376. else {
  76377. if (this._currentMeshSelected) {
  76378. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76379. }
  76380. this._currentMeshSelected = null;
  76381. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76382. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76383. }
  76384. }
  76385. }
  76386. else {
  76387. this._currentHit = null;
  76388. this._currentMeshSelected = null;
  76389. this._teleportationAllowed = false;
  76390. this._hideTeleportationTarget();
  76391. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76392. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76393. }
  76394. };
  76395. /**
  76396. * Sets the color of the laser ray from the vr controllers.
  76397. * @param color new color for the ray.
  76398. */
  76399. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76400. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76401. this._leftLaserPointer.material.emissiveColor = color;
  76402. }
  76403. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76404. this._rightLaserPointer.material.emissiveColor = color;
  76405. }
  76406. };
  76407. /**
  76408. * Sets the color of the ray from the vr headsets gaze.
  76409. * @param color new color for the ray.
  76410. */
  76411. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  76412. if (this._gazeTracker.material) {
  76413. this._gazeTracker.material.emissiveColor = color;
  76414. }
  76415. };
  76416. /**
  76417. * Exits VR and disposes of the vr experience helper
  76418. */
  76419. VRExperienceHelper.prototype.dispose = function () {
  76420. if (this.isInVRMode) {
  76421. this.exitVR();
  76422. }
  76423. if (this._passProcessMove) {
  76424. this._passProcessMove.dispose();
  76425. }
  76426. if (this._postProcessMove) {
  76427. this._postProcessMove.dispose();
  76428. }
  76429. if (this._webVRCamera) {
  76430. this._webVRCamera.dispose();
  76431. }
  76432. if (this._vrDeviceOrientationCamera) {
  76433. this._vrDeviceOrientationCamera.dispose();
  76434. }
  76435. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  76436. document.body.removeChild(this._btnVR);
  76437. }
  76438. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  76439. this._deviceOrientationCamera.dispose();
  76440. }
  76441. if (this._gazeTracker) {
  76442. this._gazeTracker.dispose();
  76443. }
  76444. if (this._teleportationTarget) {
  76445. this._teleportationTarget.dispose();
  76446. }
  76447. this._floorMeshesCollection = [];
  76448. document.removeEventListener("keydown", this._onKeyDown);
  76449. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76450. window.removeEventListener("resize", this._onResize);
  76451. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  76452. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  76453. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  76454. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  76455. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  76456. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  76457. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  76458. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76459. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  76460. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  76461. this._scene.unregisterBeforeRender(this.beforeRender);
  76462. };
  76463. /**
  76464. * Gets the name of the VRExperienceHelper class
  76465. * @returns "VRExperienceHelper"
  76466. */
  76467. VRExperienceHelper.prototype.getClassName = function () {
  76468. return "VRExperienceHelper";
  76469. };
  76470. return VRExperienceHelper;
  76471. }());
  76472. BABYLON.VRExperienceHelper = VRExperienceHelper;
  76473. })(BABYLON || (BABYLON = {}));
  76474. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  76475. // Mainly based on these 2 articles :
  76476. // 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
  76477. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  76478. var BABYLON;
  76479. (function (BABYLON) {
  76480. var JoystickAxis;
  76481. (function (JoystickAxis) {
  76482. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  76483. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  76484. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  76485. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  76486. var VirtualJoystick = /** @class */ (function () {
  76487. function VirtualJoystick(leftJoystick) {
  76488. var _this = this;
  76489. if (leftJoystick) {
  76490. this._leftJoystick = true;
  76491. }
  76492. else {
  76493. this._leftJoystick = false;
  76494. }
  76495. VirtualJoystick._globalJoystickIndex++;
  76496. // By default left & right arrow keys are moving the X
  76497. // and up & down keys are moving the Y
  76498. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76499. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76500. this.reverseLeftRight = false;
  76501. this.reverseUpDown = false;
  76502. // collections of pointers
  76503. this._touches = new BABYLON.StringDictionary();
  76504. this.deltaPosition = BABYLON.Vector3.Zero();
  76505. this._joystickSensibility = 25;
  76506. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76507. this._onResize = function (evt) {
  76508. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76509. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76510. if (VirtualJoystick.vjCanvas) {
  76511. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  76512. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  76513. }
  76514. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  76515. };
  76516. // injecting a canvas element on top of the canvas 3D game
  76517. if (!VirtualJoystick.vjCanvas) {
  76518. window.addEventListener("resize", this._onResize, false);
  76519. VirtualJoystick.vjCanvas = document.createElement("canvas");
  76520. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76521. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76522. VirtualJoystick.vjCanvas.width = window.innerWidth;
  76523. VirtualJoystick.vjCanvas.height = window.innerHeight;
  76524. VirtualJoystick.vjCanvas.style.width = "100%";
  76525. VirtualJoystick.vjCanvas.style.height = "100%";
  76526. VirtualJoystick.vjCanvas.style.position = "absolute";
  76527. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  76528. VirtualJoystick.vjCanvas.style.top = "0px";
  76529. VirtualJoystick.vjCanvas.style.left = "0px";
  76530. VirtualJoystick.vjCanvas.style.zIndex = "5";
  76531. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  76532. // Support for jQuery PEP polyfill
  76533. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  76534. var context = VirtualJoystick.vjCanvas.getContext('2d');
  76535. if (!context) {
  76536. throw new Error("Unable to create canvas for virtual joystick");
  76537. }
  76538. VirtualJoystick.vjCanvasContext = context;
  76539. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  76540. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76541. document.body.appendChild(VirtualJoystick.vjCanvas);
  76542. }
  76543. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  76544. this.pressed = false;
  76545. // default joystick color
  76546. this._joystickColor = "cyan";
  76547. this._joystickPointerID = -1;
  76548. // current joystick position
  76549. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  76550. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  76551. // origin joystick position
  76552. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  76553. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  76554. this._onPointerDownHandlerRef = function (evt) {
  76555. _this._onPointerDown(evt);
  76556. };
  76557. this._onPointerMoveHandlerRef = function (evt) {
  76558. _this._onPointerMove(evt);
  76559. };
  76560. this._onPointerUpHandlerRef = function (evt) {
  76561. _this._onPointerUp(evt);
  76562. };
  76563. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  76564. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  76565. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  76566. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  76567. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  76568. evt.preventDefault(); // Disables system menu
  76569. }, false);
  76570. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76571. }
  76572. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  76573. this._joystickSensibility = newJoystickSensibility;
  76574. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76575. };
  76576. VirtualJoystick.prototype._onPointerDown = function (e) {
  76577. var positionOnScreenCondition;
  76578. e.preventDefault();
  76579. if (this._leftJoystick === true) {
  76580. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  76581. }
  76582. else {
  76583. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  76584. }
  76585. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  76586. // First contact will be dedicated to the virtual joystick
  76587. this._joystickPointerID = e.pointerId;
  76588. this._joystickPointerStartPos.x = e.clientX;
  76589. this._joystickPointerStartPos.y = e.clientY;
  76590. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  76591. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  76592. this._deltaJoystickVector.x = 0;
  76593. this._deltaJoystickVector.y = 0;
  76594. this.pressed = true;
  76595. this._touches.add(e.pointerId.toString(), e);
  76596. }
  76597. else {
  76598. // You can only trigger the action buttons with a joystick declared
  76599. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  76600. this._action();
  76601. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  76602. }
  76603. }
  76604. };
  76605. VirtualJoystick.prototype._onPointerMove = function (e) {
  76606. // If the current pointer is the one associated to the joystick (first touch contact)
  76607. if (this._joystickPointerID == e.pointerId) {
  76608. this._joystickPointerPos.x = e.clientX;
  76609. this._joystickPointerPos.y = e.clientY;
  76610. this._deltaJoystickVector = this._joystickPointerPos.clone();
  76611. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  76612. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  76613. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  76614. switch (this._axisTargetedByLeftAndRight) {
  76615. case JoystickAxis.X:
  76616. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  76617. break;
  76618. case JoystickAxis.Y:
  76619. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  76620. break;
  76621. case JoystickAxis.Z:
  76622. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  76623. break;
  76624. }
  76625. var directionUpDown = this.reverseUpDown ? 1 : -1;
  76626. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  76627. switch (this._axisTargetedByUpAndDown) {
  76628. case JoystickAxis.X:
  76629. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  76630. break;
  76631. case JoystickAxis.Y:
  76632. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  76633. break;
  76634. case JoystickAxis.Z:
  76635. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  76636. break;
  76637. }
  76638. }
  76639. else {
  76640. var data = this._touches.get(e.pointerId.toString());
  76641. if (data) {
  76642. data.x = e.clientX;
  76643. data.y = e.clientY;
  76644. }
  76645. }
  76646. };
  76647. VirtualJoystick.prototype._onPointerUp = function (e) {
  76648. if (this._joystickPointerID == e.pointerId) {
  76649. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  76650. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  76651. this._joystickPointerID = -1;
  76652. this.pressed = false;
  76653. }
  76654. else {
  76655. var touch = this._touches.get(e.pointerId.toString());
  76656. if (touch) {
  76657. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76658. }
  76659. }
  76660. this._deltaJoystickVector.x = 0;
  76661. this._deltaJoystickVector.y = 0;
  76662. this._touches.remove(e.pointerId.toString());
  76663. };
  76664. /**
  76665. * Change the color of the virtual joystick
  76666. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  76667. */
  76668. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  76669. this._joystickColor = newColor;
  76670. };
  76671. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  76672. this._action = action;
  76673. };
  76674. // Define which axis you'd like to control for left & right
  76675. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  76676. switch (axis) {
  76677. case JoystickAxis.X:
  76678. case JoystickAxis.Y:
  76679. case JoystickAxis.Z:
  76680. this._axisTargetedByLeftAndRight = axis;
  76681. break;
  76682. default:
  76683. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76684. break;
  76685. }
  76686. };
  76687. // Define which axis you'd like to control for up & down
  76688. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  76689. switch (axis) {
  76690. case JoystickAxis.X:
  76691. case JoystickAxis.Y:
  76692. case JoystickAxis.Z:
  76693. this._axisTargetedByUpAndDown = axis;
  76694. break;
  76695. default:
  76696. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76697. break;
  76698. }
  76699. };
  76700. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  76701. var _this = this;
  76702. if (this.pressed) {
  76703. this._touches.forEach(function (key, touch) {
  76704. if (touch.pointerId === _this._joystickPointerID) {
  76705. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  76706. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  76707. VirtualJoystick.vjCanvasContext.beginPath();
  76708. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76709. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76710. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  76711. VirtualJoystick.vjCanvasContext.stroke();
  76712. VirtualJoystick.vjCanvasContext.closePath();
  76713. VirtualJoystick.vjCanvasContext.beginPath();
  76714. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76715. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76716. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  76717. VirtualJoystick.vjCanvasContext.stroke();
  76718. VirtualJoystick.vjCanvasContext.closePath();
  76719. VirtualJoystick.vjCanvasContext.beginPath();
  76720. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76721. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  76722. VirtualJoystick.vjCanvasContext.stroke();
  76723. VirtualJoystick.vjCanvasContext.closePath();
  76724. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  76725. }
  76726. else {
  76727. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76728. VirtualJoystick.vjCanvasContext.beginPath();
  76729. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  76730. VirtualJoystick.vjCanvasContext.beginPath();
  76731. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  76732. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76733. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  76734. VirtualJoystick.vjCanvasContext.stroke();
  76735. VirtualJoystick.vjCanvasContext.closePath();
  76736. touch.prevX = touch.x;
  76737. touch.prevY = touch.y;
  76738. }
  76739. ;
  76740. });
  76741. }
  76742. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76743. };
  76744. VirtualJoystick.prototype.releaseCanvas = function () {
  76745. if (VirtualJoystick.vjCanvas) {
  76746. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  76747. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  76748. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  76749. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  76750. window.removeEventListener("resize", this._onResize);
  76751. document.body.removeChild(VirtualJoystick.vjCanvas);
  76752. VirtualJoystick.vjCanvas = null;
  76753. }
  76754. };
  76755. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  76756. VirtualJoystick._globalJoystickIndex = 0;
  76757. return VirtualJoystick;
  76758. }());
  76759. BABYLON.VirtualJoystick = VirtualJoystick;
  76760. })(BABYLON || (BABYLON = {}));
  76761. //# sourceMappingURL=babylon.virtualJoystick.js.map
  76762. var BABYLON;
  76763. (function (BABYLON) {
  76764. // We're mainly based on the logic defined into the FreeCamera code
  76765. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  76766. __extends(VirtualJoysticksCamera, _super);
  76767. function VirtualJoysticksCamera(name, position, scene) {
  76768. var _this = _super.call(this, name, position, scene) || this;
  76769. _this.inputs.addVirtualJoystick();
  76770. return _this;
  76771. }
  76772. VirtualJoysticksCamera.prototype.getClassName = function () {
  76773. return "VirtualJoysticksCamera";
  76774. };
  76775. return VirtualJoysticksCamera;
  76776. }(BABYLON.FreeCamera));
  76777. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  76778. })(BABYLON || (BABYLON = {}));
  76779. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  76780. var BABYLON;
  76781. (function (BABYLON) {
  76782. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  76783. function FreeCameraVirtualJoystickInput() {
  76784. }
  76785. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  76786. return this._leftjoystick;
  76787. };
  76788. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  76789. return this._rightjoystick;
  76790. };
  76791. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  76792. if (this._leftjoystick) {
  76793. var camera = this.camera;
  76794. var speed = camera._computeLocalCameraSpeed() * 50;
  76795. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  76796. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  76797. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  76798. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  76799. if (!this._leftjoystick.pressed) {
  76800. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  76801. }
  76802. if (!this._rightjoystick.pressed) {
  76803. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  76804. }
  76805. }
  76806. };
  76807. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  76808. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  76809. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  76810. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  76811. this._leftjoystick.setJoystickSensibility(0.15);
  76812. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  76813. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  76814. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  76815. this._rightjoystick.reverseUpDown = true;
  76816. this._rightjoystick.setJoystickSensibility(0.05);
  76817. this._rightjoystick.setJoystickColor("yellow");
  76818. };
  76819. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  76820. this._leftjoystick.releaseCanvas();
  76821. this._rightjoystick.releaseCanvas();
  76822. };
  76823. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  76824. return "FreeCameraVirtualJoystickInput";
  76825. };
  76826. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  76827. return "virtualJoystick";
  76828. };
  76829. return FreeCameraVirtualJoystickInput;
  76830. }());
  76831. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  76832. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  76833. })(BABYLON || (BABYLON = {}));
  76834. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  76835. var BABYLON;
  76836. (function (BABYLON) {
  76837. var SimplificationSettings = /** @class */ (function () {
  76838. function SimplificationSettings(quality, distance, optimizeMesh) {
  76839. this.quality = quality;
  76840. this.distance = distance;
  76841. this.optimizeMesh = optimizeMesh;
  76842. }
  76843. return SimplificationSettings;
  76844. }());
  76845. BABYLON.SimplificationSettings = SimplificationSettings;
  76846. var SimplificationQueue = /** @class */ (function () {
  76847. function SimplificationQueue() {
  76848. this.running = false;
  76849. this._simplificationArray = [];
  76850. }
  76851. SimplificationQueue.prototype.addTask = function (task) {
  76852. this._simplificationArray.push(task);
  76853. };
  76854. SimplificationQueue.prototype.executeNext = function () {
  76855. var task = this._simplificationArray.pop();
  76856. if (task) {
  76857. this.running = true;
  76858. this.runSimplification(task);
  76859. }
  76860. else {
  76861. this.running = false;
  76862. }
  76863. };
  76864. SimplificationQueue.prototype.runSimplification = function (task) {
  76865. var _this = this;
  76866. if (task.parallelProcessing) {
  76867. //parallel simplifier
  76868. task.settings.forEach(function (setting) {
  76869. var simplifier = _this.getSimplifier(task);
  76870. simplifier.simplify(setting, function (newMesh) {
  76871. task.mesh.addLODLevel(setting.distance, newMesh);
  76872. newMesh.isVisible = true;
  76873. //check if it is the last
  76874. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  76875. //all done, run the success callback.
  76876. task.successCallback();
  76877. }
  76878. _this.executeNext();
  76879. });
  76880. });
  76881. }
  76882. else {
  76883. //single simplifier.
  76884. var simplifier = this.getSimplifier(task);
  76885. var runDecimation = function (setting, callback) {
  76886. simplifier.simplify(setting, function (newMesh) {
  76887. task.mesh.addLODLevel(setting.distance, newMesh);
  76888. newMesh.isVisible = true;
  76889. //run the next quality level
  76890. callback();
  76891. });
  76892. };
  76893. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  76894. runDecimation(task.settings[loop.index], function () {
  76895. loop.executeNext();
  76896. });
  76897. }, function () {
  76898. //execution ended, run the success callback.
  76899. if (task.successCallback) {
  76900. task.successCallback();
  76901. }
  76902. _this.executeNext();
  76903. });
  76904. }
  76905. };
  76906. SimplificationQueue.prototype.getSimplifier = function (task) {
  76907. switch (task.simplificationType) {
  76908. case SimplificationType.QUADRATIC:
  76909. default:
  76910. return new QuadraticErrorSimplification(task.mesh);
  76911. }
  76912. };
  76913. return SimplificationQueue;
  76914. }());
  76915. BABYLON.SimplificationQueue = SimplificationQueue;
  76916. /**
  76917. * The implemented types of simplification.
  76918. * At the moment only Quadratic Error Decimation is implemented.
  76919. */
  76920. var SimplificationType;
  76921. (function (SimplificationType) {
  76922. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  76923. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  76924. var DecimationTriangle = /** @class */ (function () {
  76925. function DecimationTriangle(vertices) {
  76926. this.vertices = vertices;
  76927. this.error = new Array(4);
  76928. this.deleted = false;
  76929. this.isDirty = false;
  76930. this.deletePending = false;
  76931. this.borderFactor = 0;
  76932. }
  76933. return DecimationTriangle;
  76934. }());
  76935. BABYLON.DecimationTriangle = DecimationTriangle;
  76936. var DecimationVertex = /** @class */ (function () {
  76937. function DecimationVertex(position, id) {
  76938. this.position = position;
  76939. this.id = id;
  76940. this.isBorder = true;
  76941. this.q = new QuadraticMatrix();
  76942. this.triangleCount = 0;
  76943. this.triangleStart = 0;
  76944. this.originalOffsets = [];
  76945. }
  76946. DecimationVertex.prototype.updatePosition = function (newPosition) {
  76947. this.position.copyFrom(newPosition);
  76948. };
  76949. return DecimationVertex;
  76950. }());
  76951. BABYLON.DecimationVertex = DecimationVertex;
  76952. var QuadraticMatrix = /** @class */ (function () {
  76953. function QuadraticMatrix(data) {
  76954. this.data = new Array(10);
  76955. for (var i = 0; i < 10; ++i) {
  76956. if (data && data[i]) {
  76957. this.data[i] = data[i];
  76958. }
  76959. else {
  76960. this.data[i] = 0;
  76961. }
  76962. }
  76963. }
  76964. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  76965. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  76966. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  76967. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  76968. return det;
  76969. };
  76970. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  76971. for (var i = 0; i < 10; ++i) {
  76972. this.data[i] += matrix.data[i];
  76973. }
  76974. };
  76975. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  76976. for (var i = 0; i < 10; ++i) {
  76977. this.data[i] += data[i];
  76978. }
  76979. };
  76980. QuadraticMatrix.prototype.add = function (matrix) {
  76981. var m = new QuadraticMatrix();
  76982. for (var i = 0; i < 10; ++i) {
  76983. m.data[i] = this.data[i] + matrix.data[i];
  76984. }
  76985. return m;
  76986. };
  76987. QuadraticMatrix.FromData = function (a, b, c, d) {
  76988. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  76989. };
  76990. //returning an array to avoid garbage collection
  76991. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  76992. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  76993. };
  76994. return QuadraticMatrix;
  76995. }());
  76996. BABYLON.QuadraticMatrix = QuadraticMatrix;
  76997. var Reference = /** @class */ (function () {
  76998. function Reference(vertexId, triangleId) {
  76999. this.vertexId = vertexId;
  77000. this.triangleId = triangleId;
  77001. }
  77002. return Reference;
  77003. }());
  77004. BABYLON.Reference = Reference;
  77005. /**
  77006. * An implementation of the Quadratic Error simplification algorithm.
  77007. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  77008. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  77009. * @author RaananW
  77010. */
  77011. var QuadraticErrorSimplification = /** @class */ (function () {
  77012. function QuadraticErrorSimplification(_mesh) {
  77013. this._mesh = _mesh;
  77014. this.syncIterations = 5000;
  77015. this.aggressiveness = 7;
  77016. this.decimationIterations = 100;
  77017. this.boundingBoxEpsilon = BABYLON.Epsilon;
  77018. }
  77019. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  77020. var _this = this;
  77021. this.initDecimatedMesh();
  77022. //iterating through the submeshes array, one after the other.
  77023. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  77024. _this.initWithMesh(loop.index, function () {
  77025. _this.runDecimation(settings, loop.index, function () {
  77026. loop.executeNext();
  77027. });
  77028. }, settings.optimizeMesh);
  77029. }, function () {
  77030. setTimeout(function () {
  77031. successCallback(_this._reconstructedMesh);
  77032. }, 0);
  77033. });
  77034. };
  77035. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  77036. var _this = this;
  77037. var targetCount = ~~(this.triangles.length * settings.quality);
  77038. var deletedTriangles = 0;
  77039. var triangleCount = this.triangles.length;
  77040. var iterationFunction = function (iteration, callback) {
  77041. setTimeout(function () {
  77042. if (iteration % 5 === 0) {
  77043. _this.updateMesh(iteration === 0);
  77044. }
  77045. for (var i = 0; i < _this.triangles.length; ++i) {
  77046. _this.triangles[i].isDirty = false;
  77047. }
  77048. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  77049. var trianglesIterator = function (i) {
  77050. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  77051. var t = _this.triangles[tIdx];
  77052. if (!t)
  77053. return;
  77054. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  77055. return;
  77056. }
  77057. for (var j = 0; j < 3; ++j) {
  77058. if (t.error[j] < threshold) {
  77059. var deleted0 = [];
  77060. var deleted1 = [];
  77061. var v0 = t.vertices[j];
  77062. var v1 = t.vertices[(j + 1) % 3];
  77063. if (v0.isBorder || v1.isBorder)
  77064. continue;
  77065. var p = BABYLON.Vector3.Zero();
  77066. var n = BABYLON.Vector3.Zero();
  77067. var uv = BABYLON.Vector2.Zero();
  77068. var color = new BABYLON.Color4(0, 0, 0, 1);
  77069. _this.calculateError(v0, v1, p, n, uv, color);
  77070. var delTr = new Array();
  77071. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  77072. continue;
  77073. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  77074. continue;
  77075. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  77076. continue;
  77077. var uniqueArray = new Array();
  77078. delTr.forEach(function (deletedT) {
  77079. if (uniqueArray.indexOf(deletedT) === -1) {
  77080. deletedT.deletePending = true;
  77081. uniqueArray.push(deletedT);
  77082. }
  77083. });
  77084. if (uniqueArray.length % 2 !== 0) {
  77085. continue;
  77086. }
  77087. v0.q = v1.q.add(v0.q);
  77088. v0.updatePosition(p);
  77089. var tStart = _this.references.length;
  77090. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  77091. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  77092. var tCount = _this.references.length - tStart;
  77093. if (tCount <= v0.triangleCount) {
  77094. if (tCount) {
  77095. for (var c = 0; c < tCount; c++) {
  77096. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  77097. }
  77098. }
  77099. }
  77100. else {
  77101. v0.triangleStart = tStart;
  77102. }
  77103. v0.triangleCount = tCount;
  77104. break;
  77105. }
  77106. }
  77107. };
  77108. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  77109. }, 0);
  77110. };
  77111. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  77112. if (triangleCount - deletedTriangles <= targetCount)
  77113. loop.breakLoop();
  77114. else {
  77115. iterationFunction(loop.index, function () {
  77116. loop.executeNext();
  77117. });
  77118. }
  77119. }, function () {
  77120. setTimeout(function () {
  77121. //reconstruct this part of the mesh
  77122. _this.reconstructMesh(submeshIndex);
  77123. successCallback();
  77124. }, 0);
  77125. });
  77126. };
  77127. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  77128. var _this = this;
  77129. this.vertices = [];
  77130. this.triangles = [];
  77131. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  77132. var indices = this._mesh.getIndices();
  77133. var submesh = this._mesh.subMeshes[submeshIndex];
  77134. var findInVertices = function (positionToSearch) {
  77135. if (optimizeMesh) {
  77136. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  77137. if (_this.vertices[ii].position.equals(positionToSearch)) {
  77138. return _this.vertices[ii];
  77139. }
  77140. }
  77141. }
  77142. return null;
  77143. };
  77144. var vertexReferences = [];
  77145. var vertexInit = function (i) {
  77146. if (!positionData) {
  77147. return;
  77148. }
  77149. var offset = i + submesh.verticesStart;
  77150. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  77151. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  77152. vertex.originalOffsets.push(offset);
  77153. if (vertex.id === _this.vertices.length) {
  77154. _this.vertices.push(vertex);
  77155. }
  77156. vertexReferences.push(vertex.id);
  77157. };
  77158. //var totalVertices = mesh.getTotalVertices();
  77159. var totalVertices = submesh.verticesCount;
  77160. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  77161. var indicesInit = function (i) {
  77162. if (!indices) {
  77163. return;
  77164. }
  77165. var offset = (submesh.indexStart / 3) + i;
  77166. var pos = (offset * 3);
  77167. var i0 = indices[pos + 0];
  77168. var i1 = indices[pos + 1];
  77169. var i2 = indices[pos + 2];
  77170. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  77171. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  77172. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  77173. var triangle = new DecimationTriangle([v0, v1, v2]);
  77174. triangle.originalOffset = pos;
  77175. _this.triangles.push(triangle);
  77176. };
  77177. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  77178. _this.init(callback);
  77179. });
  77180. });
  77181. };
  77182. QuadraticErrorSimplification.prototype.init = function (callback) {
  77183. var _this = this;
  77184. var triangleInit1 = function (i) {
  77185. var t = _this.triangles[i];
  77186. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  77187. for (var j = 0; j < 3; j++) {
  77188. 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))));
  77189. }
  77190. };
  77191. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  77192. var triangleInit2 = function (i) {
  77193. var t = _this.triangles[i];
  77194. for (var j = 0; j < 3; ++j) {
  77195. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  77196. }
  77197. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77198. };
  77199. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  77200. callback();
  77201. });
  77202. });
  77203. };
  77204. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  77205. var newTriangles = [];
  77206. var i;
  77207. for (i = 0; i < this.vertices.length; ++i) {
  77208. this.vertices[i].triangleCount = 0;
  77209. }
  77210. var t;
  77211. var j;
  77212. for (i = 0; i < this.triangles.length; ++i) {
  77213. if (!this.triangles[i].deleted) {
  77214. t = this.triangles[i];
  77215. for (j = 0; j < 3; ++j) {
  77216. t.vertices[j].triangleCount = 1;
  77217. }
  77218. newTriangles.push(t);
  77219. }
  77220. }
  77221. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  77222. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  77223. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  77224. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  77225. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  77226. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  77227. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  77228. var vertexCount = 0;
  77229. for (i = 0; i < this.vertices.length; ++i) {
  77230. var vertex = this.vertices[i];
  77231. vertex.id = vertexCount;
  77232. if (vertex.triangleCount) {
  77233. vertex.originalOffsets.forEach(function (originalOffset) {
  77234. if (!normalData) {
  77235. return;
  77236. }
  77237. newPositionData.push(vertex.position.x);
  77238. newPositionData.push(vertex.position.y);
  77239. newPositionData.push(vertex.position.z);
  77240. newNormalData.push(normalData[originalOffset * 3]);
  77241. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  77242. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  77243. if (uvs && uvs.length) {
  77244. newUVsData.push(uvs[(originalOffset * 2)]);
  77245. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  77246. }
  77247. else if (colorsData && colorsData.length) {
  77248. newColorsData.push(colorsData[(originalOffset * 4)]);
  77249. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  77250. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  77251. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  77252. }
  77253. ++vertexCount;
  77254. });
  77255. }
  77256. }
  77257. var startingIndex = this._reconstructedMesh.getTotalIndices();
  77258. var startingVertex = this._reconstructedMesh.getTotalVertices();
  77259. var submeshesArray = this._reconstructedMesh.subMeshes;
  77260. this._reconstructedMesh.subMeshes = [];
  77261. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  77262. var originalIndices = this._mesh.getIndices();
  77263. for (i = 0; i < newTriangles.length; ++i) {
  77264. t = newTriangles[i]; //now get the new referencing point for each vertex
  77265. [0, 1, 2].forEach(function (idx) {
  77266. var id = originalIndices[t.originalOffset + idx];
  77267. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  77268. if (offset < 0)
  77269. offset = 0;
  77270. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  77271. });
  77272. }
  77273. //overwriting the old vertex buffers and indices.
  77274. this._reconstructedMesh.setIndices(newIndicesArray);
  77275. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  77276. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  77277. if (newUVsData.length > 0)
  77278. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  77279. if (newColorsData.length > 0)
  77280. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  77281. //create submesh
  77282. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  77283. if (submeshIndex > 0) {
  77284. this._reconstructedMesh.subMeshes = [];
  77285. submeshesArray.forEach(function (submesh) {
  77286. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  77287. });
  77288. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  77289. }
  77290. };
  77291. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  77292. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  77293. this._reconstructedMesh.material = this._mesh.material;
  77294. this._reconstructedMesh.parent = this._mesh.parent;
  77295. this._reconstructedMesh.isVisible = false;
  77296. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  77297. };
  77298. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  77299. for (var i = 0; i < vertex1.triangleCount; ++i) {
  77300. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  77301. if (t.deleted)
  77302. continue;
  77303. var s = this.references[vertex1.triangleStart + i].vertexId;
  77304. var v1 = t.vertices[(s + 1) % 3];
  77305. var v2 = t.vertices[(s + 2) % 3];
  77306. if ((v1 === vertex2 || v2 === vertex2)) {
  77307. deletedArray[i] = true;
  77308. delTr.push(t);
  77309. continue;
  77310. }
  77311. var d1 = v1.position.subtract(point);
  77312. d1 = d1.normalize();
  77313. var d2 = v2.position.subtract(point);
  77314. d2 = d2.normalize();
  77315. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  77316. return true;
  77317. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  77318. deletedArray[i] = false;
  77319. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  77320. return true;
  77321. }
  77322. return false;
  77323. };
  77324. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  77325. var newDeleted = deletedTriangles;
  77326. for (var i = 0; i < vertex.triangleCount; ++i) {
  77327. var ref = this.references[vertex.triangleStart + i];
  77328. var t = this.triangles[ref.triangleId];
  77329. if (t.deleted)
  77330. continue;
  77331. if (deletedArray[i] && t.deletePending) {
  77332. t.deleted = true;
  77333. newDeleted++;
  77334. continue;
  77335. }
  77336. t.vertices[ref.vertexId] = origVertex;
  77337. t.isDirty = true;
  77338. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  77339. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  77340. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  77341. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77342. this.references.push(ref);
  77343. }
  77344. return newDeleted;
  77345. };
  77346. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  77347. for (var i = 0; i < this.vertices.length; ++i) {
  77348. var vCount = [];
  77349. var vId = [];
  77350. var v = this.vertices[i];
  77351. var j;
  77352. for (j = 0; j < v.triangleCount; ++j) {
  77353. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77354. for (var ii = 0; ii < 3; ii++) {
  77355. var ofs = 0;
  77356. var vv = triangle.vertices[ii];
  77357. while (ofs < vCount.length) {
  77358. if (vId[ofs] === vv.id)
  77359. break;
  77360. ++ofs;
  77361. }
  77362. if (ofs === vCount.length) {
  77363. vCount.push(1);
  77364. vId.push(vv.id);
  77365. }
  77366. else {
  77367. vCount[ofs]++;
  77368. }
  77369. }
  77370. }
  77371. for (j = 0; j < vCount.length; ++j) {
  77372. if (vCount[j] === 1) {
  77373. this.vertices[vId[j]].isBorder = true;
  77374. }
  77375. else {
  77376. this.vertices[vId[j]].isBorder = false;
  77377. }
  77378. }
  77379. }
  77380. };
  77381. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77382. if (identifyBorders === void 0) { identifyBorders = false; }
  77383. var i;
  77384. if (!identifyBorders) {
  77385. var newTrianglesVector = [];
  77386. for (i = 0; i < this.triangles.length; ++i) {
  77387. if (!this.triangles[i].deleted) {
  77388. newTrianglesVector.push(this.triangles[i]);
  77389. }
  77390. }
  77391. this.triangles = newTrianglesVector;
  77392. }
  77393. for (i = 0; i < this.vertices.length; ++i) {
  77394. this.vertices[i].triangleCount = 0;
  77395. this.vertices[i].triangleStart = 0;
  77396. }
  77397. var t;
  77398. var j;
  77399. var v;
  77400. for (i = 0; i < this.triangles.length; ++i) {
  77401. t = this.triangles[i];
  77402. for (j = 0; j < 3; ++j) {
  77403. v = t.vertices[j];
  77404. v.triangleCount++;
  77405. }
  77406. }
  77407. var tStart = 0;
  77408. for (i = 0; i < this.vertices.length; ++i) {
  77409. this.vertices[i].triangleStart = tStart;
  77410. tStart += this.vertices[i].triangleCount;
  77411. this.vertices[i].triangleCount = 0;
  77412. }
  77413. var newReferences = new Array(this.triangles.length * 3);
  77414. for (i = 0; i < this.triangles.length; ++i) {
  77415. t = this.triangles[i];
  77416. for (j = 0; j < 3; ++j) {
  77417. v = t.vertices[j];
  77418. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  77419. v.triangleCount++;
  77420. }
  77421. }
  77422. this.references = newReferences;
  77423. if (identifyBorders) {
  77424. this.identifyBorder();
  77425. }
  77426. };
  77427. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  77428. var x = point.x;
  77429. var y = point.y;
  77430. var z = point.z;
  77431. 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
  77432. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  77433. };
  77434. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  77435. var q = vertex1.q.add(vertex2.q);
  77436. var border = vertex1.isBorder && vertex2.isBorder;
  77437. var error = 0;
  77438. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  77439. if (qDet !== 0 && !border) {
  77440. if (!pointResult) {
  77441. pointResult = BABYLON.Vector3.Zero();
  77442. }
  77443. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  77444. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  77445. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  77446. error = this.vertexError(q, pointResult);
  77447. }
  77448. else {
  77449. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  77450. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  77451. var error1 = this.vertexError(q, vertex1.position);
  77452. var error2 = this.vertexError(q, vertex2.position);
  77453. var error3 = this.vertexError(q, p3);
  77454. error = Math.min(error1, error2, error3);
  77455. if (error === error1) {
  77456. if (pointResult) {
  77457. pointResult.copyFrom(vertex1.position);
  77458. }
  77459. }
  77460. else if (error === error2) {
  77461. if (pointResult) {
  77462. pointResult.copyFrom(vertex2.position);
  77463. }
  77464. }
  77465. else {
  77466. if (pointResult) {
  77467. pointResult.copyFrom(p3);
  77468. }
  77469. }
  77470. }
  77471. return error;
  77472. };
  77473. return QuadraticErrorSimplification;
  77474. }());
  77475. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  77476. })(BABYLON || (BABYLON = {}));
  77477. //# sourceMappingURL=babylon.meshSimplification.js.map
  77478. var BABYLON;
  77479. (function (BABYLON) {
  77480. var MeshLODLevel = /** @class */ (function () {
  77481. function MeshLODLevel(distance, mesh) {
  77482. this.distance = distance;
  77483. this.mesh = mesh;
  77484. }
  77485. return MeshLODLevel;
  77486. }());
  77487. BABYLON.MeshLODLevel = MeshLODLevel;
  77488. })(BABYLON || (BABYLON = {}));
  77489. //# sourceMappingURL=babylon.meshLODLevel.js.map
  77490. var BABYLON;
  77491. (function (BABYLON) {
  77492. /**
  77493. * Defines the root class used to create scene optimization to use with SceneOptimizer
  77494. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77495. */
  77496. var SceneOptimization = /** @class */ (function () {
  77497. /**
  77498. * Creates the SceneOptimization object
  77499. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77500. * @param desc defines the description associated with the optimization
  77501. */
  77502. function SceneOptimization(
  77503. /**
  77504. * Defines the priority of this optimization (0 by default which means first in the list)
  77505. */
  77506. priority) {
  77507. if (priority === void 0) { priority = 0; }
  77508. this.priority = priority;
  77509. }
  77510. /**
  77511. * Gets a string describing the action executed by the current optimization
  77512. * @returns description string
  77513. */
  77514. SceneOptimization.prototype.getDescription = function () {
  77515. return "";
  77516. };
  77517. /**
  77518. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77519. * @param scene defines the current scene where to apply this optimization
  77520. * @param optimizer defines the current optimizer
  77521. * @returns true if everything that can be done was applied
  77522. */
  77523. SceneOptimization.prototype.apply = function (scene, optimizer) {
  77524. return true;
  77525. };
  77526. ;
  77527. return SceneOptimization;
  77528. }());
  77529. BABYLON.SceneOptimization = SceneOptimization;
  77530. /**
  77531. * Defines an optimization used to reduce the size of render target textures
  77532. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77533. */
  77534. var TextureOptimization = /** @class */ (function (_super) {
  77535. __extends(TextureOptimization, _super);
  77536. /**
  77537. * Creates the TextureOptimization object
  77538. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77539. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77540. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77541. */
  77542. function TextureOptimization(
  77543. /**
  77544. * Defines the priority of this optimization (0 by default which means first in the list)
  77545. */
  77546. priority,
  77547. /**
  77548. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77549. */
  77550. maximumSize,
  77551. /**
  77552. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77553. */
  77554. step) {
  77555. if (priority === void 0) { priority = 0; }
  77556. if (maximumSize === void 0) { maximumSize = 1024; }
  77557. if (step === void 0) { step = 0.5; }
  77558. var _this = _super.call(this, priority) || this;
  77559. _this.priority = priority;
  77560. _this.maximumSize = maximumSize;
  77561. _this.step = step;
  77562. return _this;
  77563. }
  77564. /**
  77565. * Gets a string describing the action executed by the current optimization
  77566. * @returns description string
  77567. */
  77568. TextureOptimization.prototype.getDescription = function () {
  77569. return "Reducing render target texture size to " + this.maximumSize;
  77570. };
  77571. /**
  77572. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77573. * @param scene defines the current scene where to apply this optimization
  77574. * @param optimizer defines the current optimizer
  77575. * @returns true if everything that can be done was applied
  77576. */
  77577. TextureOptimization.prototype.apply = function (scene, optimizer) {
  77578. var allDone = true;
  77579. for (var index = 0; index < scene.textures.length; index++) {
  77580. var texture = scene.textures[index];
  77581. if (!texture.canRescale || texture.getContext) {
  77582. continue;
  77583. }
  77584. var currentSize = texture.getSize();
  77585. var maxDimension = Math.max(currentSize.width, currentSize.height);
  77586. if (maxDimension > this.maximumSize) {
  77587. texture.scale(this.step);
  77588. allDone = false;
  77589. }
  77590. }
  77591. return allDone;
  77592. };
  77593. return TextureOptimization;
  77594. }(SceneOptimization));
  77595. BABYLON.TextureOptimization = TextureOptimization;
  77596. /**
  77597. * Defines an optimization used to increase or decrease the rendering resolution
  77598. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77599. */
  77600. var HardwareScalingOptimization = /** @class */ (function (_super) {
  77601. __extends(HardwareScalingOptimization, _super);
  77602. /**
  77603. * Creates the HardwareScalingOptimization object
  77604. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77605. * @param maximumScale defines the maximum scale to use (2 by default)
  77606. * @param step defines the step to use between two passes (0.5 by default)
  77607. */
  77608. function HardwareScalingOptimization(
  77609. /**
  77610. * Defines the priority of this optimization (0 by default which means first in the list)
  77611. */
  77612. priority,
  77613. /**
  77614. * Defines the maximum scale to use (2 by default)
  77615. */
  77616. maximumScale,
  77617. /**
  77618. * Defines the step to use between two passes (0.5 by default)
  77619. */
  77620. step) {
  77621. if (priority === void 0) { priority = 0; }
  77622. if (maximumScale === void 0) { maximumScale = 2; }
  77623. if (step === void 0) { step = 0.25; }
  77624. var _this = _super.call(this, priority) || this;
  77625. _this.priority = priority;
  77626. _this.maximumScale = maximumScale;
  77627. _this.step = step;
  77628. _this._currentScale = -1;
  77629. _this._directionOffset = 1;
  77630. return _this;
  77631. }
  77632. /**
  77633. * Gets a string describing the action executed by the current optimization
  77634. * @return description string
  77635. */
  77636. HardwareScalingOptimization.prototype.getDescription = function () {
  77637. return "Setting hardware scaling level to " + this._currentScale;
  77638. };
  77639. /**
  77640. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77641. * @param scene defines the current scene where to apply this optimization
  77642. * @param optimizer defines the current optimizer
  77643. * @returns true if everything that can be done was applied
  77644. */
  77645. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  77646. if (this._currentScale === -1) {
  77647. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  77648. if (this._currentScale > this.maximumScale) {
  77649. this._directionOffset = -1;
  77650. }
  77651. }
  77652. this._currentScale += this._directionOffset * this.step;
  77653. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  77654. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  77655. };
  77656. ;
  77657. return HardwareScalingOptimization;
  77658. }(SceneOptimization));
  77659. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  77660. /**
  77661. * Defines an optimization used to remove shadows
  77662. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77663. */
  77664. var ShadowsOptimization = /** @class */ (function (_super) {
  77665. __extends(ShadowsOptimization, _super);
  77666. function ShadowsOptimization() {
  77667. return _super !== null && _super.apply(this, arguments) || this;
  77668. }
  77669. /**
  77670. * Gets a string describing the action executed by the current optimization
  77671. * @return description string
  77672. */
  77673. ShadowsOptimization.prototype.getDescription = function () {
  77674. return "Turning shadows on/off";
  77675. };
  77676. /**
  77677. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77678. * @param scene defines the current scene where to apply this optimization
  77679. * @param optimizer defines the current optimizer
  77680. * @returns true if everything that can be done was applied
  77681. */
  77682. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  77683. scene.shadowsEnabled = optimizer.isInImprovementMode;
  77684. return true;
  77685. };
  77686. ;
  77687. return ShadowsOptimization;
  77688. }(SceneOptimization));
  77689. BABYLON.ShadowsOptimization = ShadowsOptimization;
  77690. /**
  77691. * Defines an optimization used to turn post-processes off
  77692. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77693. */
  77694. var PostProcessesOptimization = /** @class */ (function (_super) {
  77695. __extends(PostProcessesOptimization, _super);
  77696. function PostProcessesOptimization() {
  77697. return _super !== null && _super.apply(this, arguments) || this;
  77698. }
  77699. /**
  77700. * Gets a string describing the action executed by the current optimization
  77701. * @return description string
  77702. */
  77703. PostProcessesOptimization.prototype.getDescription = function () {
  77704. return "Turning post-processes on/off";
  77705. };
  77706. /**
  77707. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77708. * @param scene defines the current scene where to apply this optimization
  77709. * @param optimizer defines the current optimizer
  77710. * @returns true if everything that can be done was applied
  77711. */
  77712. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  77713. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  77714. return true;
  77715. };
  77716. ;
  77717. return PostProcessesOptimization;
  77718. }(SceneOptimization));
  77719. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  77720. /**
  77721. * Defines an optimization used to turn lens flares off
  77722. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77723. */
  77724. var LensFlaresOptimization = /** @class */ (function (_super) {
  77725. __extends(LensFlaresOptimization, _super);
  77726. function LensFlaresOptimization() {
  77727. return _super !== null && _super.apply(this, arguments) || this;
  77728. }
  77729. /**
  77730. * Gets a string describing the action executed by the current optimization
  77731. * @return description string
  77732. */
  77733. LensFlaresOptimization.prototype.getDescription = function () {
  77734. return "Turning lens flares on/off";
  77735. };
  77736. /**
  77737. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77738. * @param scene defines the current scene where to apply this optimization
  77739. * @param optimizer defines the current optimizer
  77740. * @returns true if everything that can be done was applied
  77741. */
  77742. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  77743. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  77744. return true;
  77745. };
  77746. ;
  77747. return LensFlaresOptimization;
  77748. }(SceneOptimization));
  77749. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  77750. /**
  77751. * Defines an optimization based on user defined callback.
  77752. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77753. */
  77754. var CustomOptimization = /** @class */ (function (_super) {
  77755. __extends(CustomOptimization, _super);
  77756. function CustomOptimization() {
  77757. return _super !== null && _super.apply(this, arguments) || this;
  77758. }
  77759. /**
  77760. * Gets a string describing the action executed by the current optimization
  77761. * @returns description string
  77762. */
  77763. CustomOptimization.prototype.getDescription = function () {
  77764. if (this.onGetDescription) {
  77765. return this.onGetDescription();
  77766. }
  77767. return "Running user defined callback";
  77768. };
  77769. /**
  77770. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77771. * @param scene defines the current scene where to apply this optimization
  77772. * @param optimizer defines the current optimizer
  77773. * @returns true if everything that can be done was applied
  77774. */
  77775. CustomOptimization.prototype.apply = function (scene, optimizer) {
  77776. if (this.onApply) {
  77777. return this.onApply(scene, optimizer);
  77778. }
  77779. return true;
  77780. };
  77781. ;
  77782. return CustomOptimization;
  77783. }(SceneOptimization));
  77784. BABYLON.CustomOptimization = CustomOptimization;
  77785. /**
  77786. * Defines an optimization used to turn particles off
  77787. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77788. */
  77789. var ParticlesOptimization = /** @class */ (function (_super) {
  77790. __extends(ParticlesOptimization, _super);
  77791. function ParticlesOptimization() {
  77792. return _super !== null && _super.apply(this, arguments) || this;
  77793. }
  77794. /**
  77795. * Gets a string describing the action executed by the current optimization
  77796. * @return description string
  77797. */
  77798. ParticlesOptimization.prototype.getDescription = function () {
  77799. return "Turning particles on/off";
  77800. };
  77801. /**
  77802. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77803. * @param scene defines the current scene where to apply this optimization
  77804. * @param optimizer defines the current optimizer
  77805. * @returns true if everything that can be done was applied
  77806. */
  77807. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  77808. scene.particlesEnabled = optimizer.isInImprovementMode;
  77809. return true;
  77810. };
  77811. ;
  77812. return ParticlesOptimization;
  77813. }(SceneOptimization));
  77814. BABYLON.ParticlesOptimization = ParticlesOptimization;
  77815. /**
  77816. * Defines an optimization used to turn render targets off
  77817. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77818. */
  77819. var RenderTargetsOptimization = /** @class */ (function (_super) {
  77820. __extends(RenderTargetsOptimization, _super);
  77821. function RenderTargetsOptimization() {
  77822. return _super !== null && _super.apply(this, arguments) || this;
  77823. }
  77824. /**
  77825. * Gets a string describing the action executed by the current optimization
  77826. * @return description string
  77827. */
  77828. RenderTargetsOptimization.prototype.getDescription = function () {
  77829. return "Turning render targets off";
  77830. };
  77831. /**
  77832. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77833. * @param scene defines the current scene where to apply this optimization
  77834. * @param optimizer defines the current optimizer
  77835. * @returns true if everything that can be done was applied
  77836. */
  77837. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  77838. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  77839. return true;
  77840. };
  77841. ;
  77842. return RenderTargetsOptimization;
  77843. }(SceneOptimization));
  77844. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  77845. /**
  77846. * Defines an optimization used to merge meshes with compatible materials
  77847. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77848. */
  77849. var MergeMeshesOptimization = /** @class */ (function (_super) {
  77850. __extends(MergeMeshesOptimization, _super);
  77851. function MergeMeshesOptimization() {
  77852. var _this = _super !== null && _super.apply(this, arguments) || this;
  77853. _this._canBeMerged = function (abstractMesh) {
  77854. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  77855. return false;
  77856. }
  77857. var mesh = abstractMesh;
  77858. if (!mesh.isVisible || !mesh.isEnabled()) {
  77859. return false;
  77860. }
  77861. if (mesh.instances.length > 0) {
  77862. return false;
  77863. }
  77864. if (mesh.skeleton || mesh.hasLODLevels) {
  77865. return false;
  77866. }
  77867. if (mesh.parent) {
  77868. return false;
  77869. }
  77870. return true;
  77871. };
  77872. return _this;
  77873. }
  77874. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  77875. /**
  77876. * Gets or sets a boolean which defines if optimization octree has to be updated
  77877. */
  77878. get: function () {
  77879. return MergeMeshesOptimization._UpdateSelectionTree;
  77880. },
  77881. /**
  77882. * Gets or sets a boolean which defines if optimization octree has to be updated
  77883. */
  77884. set: function (value) {
  77885. MergeMeshesOptimization._UpdateSelectionTree = value;
  77886. },
  77887. enumerable: true,
  77888. configurable: true
  77889. });
  77890. /**
  77891. * Gets a string describing the action executed by the current optimization
  77892. * @return description string
  77893. */
  77894. MergeMeshesOptimization.prototype.getDescription = function () {
  77895. return "Merging similar meshes together";
  77896. };
  77897. /**
  77898. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77899. * @param scene defines the current scene where to apply this optimization
  77900. * @param optimizer defines the current optimizer
  77901. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  77902. * @returns true if everything that can be done was applied
  77903. */
  77904. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  77905. var globalPool = scene.meshes.slice(0);
  77906. var globalLength = globalPool.length;
  77907. for (var index = 0; index < globalLength; index++) {
  77908. var currentPool = new Array();
  77909. var current = globalPool[index];
  77910. // Checks
  77911. if (!this._canBeMerged(current)) {
  77912. continue;
  77913. }
  77914. currentPool.push(current);
  77915. // Find compatible meshes
  77916. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  77917. var otherMesh = globalPool[subIndex];
  77918. if (!this._canBeMerged(otherMesh)) {
  77919. continue;
  77920. }
  77921. if (otherMesh.material !== current.material) {
  77922. continue;
  77923. }
  77924. if (otherMesh.checkCollisions !== current.checkCollisions) {
  77925. continue;
  77926. }
  77927. currentPool.push(otherMesh);
  77928. globalLength--;
  77929. globalPool.splice(subIndex, 1);
  77930. subIndex--;
  77931. }
  77932. if (currentPool.length < 2) {
  77933. continue;
  77934. }
  77935. // Merge meshes
  77936. BABYLON.Mesh.MergeMeshes(currentPool);
  77937. }
  77938. if (updateSelectionTree != undefined) {
  77939. if (updateSelectionTree) {
  77940. scene.createOrUpdateSelectionOctree();
  77941. }
  77942. }
  77943. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  77944. scene.createOrUpdateSelectionOctree();
  77945. }
  77946. return true;
  77947. };
  77948. ;
  77949. MergeMeshesOptimization._UpdateSelectionTree = false;
  77950. return MergeMeshesOptimization;
  77951. }(SceneOptimization));
  77952. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  77953. /**
  77954. * Defines a list of options used by SceneOptimizer
  77955. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77956. */
  77957. var SceneOptimizerOptions = /** @class */ (function () {
  77958. /**
  77959. * Creates a new list of options used by SceneOptimizer
  77960. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  77961. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  77962. */
  77963. function SceneOptimizerOptions(
  77964. /**
  77965. * Defines the target frame rate to reach (60 by default)
  77966. */
  77967. targetFrameRate,
  77968. /**
  77969. * Defines the interval between two checkes (2000ms by default)
  77970. */
  77971. trackerDuration) {
  77972. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  77973. if (trackerDuration === void 0) { trackerDuration = 2000; }
  77974. this.targetFrameRate = targetFrameRate;
  77975. this.trackerDuration = trackerDuration;
  77976. /**
  77977. * Gets the list of optimizations to apply
  77978. */
  77979. this.optimizations = new Array();
  77980. }
  77981. /**
  77982. * Add a new optimization
  77983. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  77984. * @returns the current SceneOptimizerOptions
  77985. */
  77986. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  77987. this.optimizations.push(optimization);
  77988. return this;
  77989. };
  77990. /**
  77991. * Add a new custom optimization
  77992. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  77993. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  77994. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77995. * @returns the current SceneOptimizerOptions
  77996. */
  77997. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  77998. if (priority === void 0) { priority = 0; }
  77999. var optimization = new CustomOptimization(priority);
  78000. optimization.onApply = onApply;
  78001. optimization.onGetDescription = onGetDescription;
  78002. this.optimizations.push(optimization);
  78003. return this;
  78004. };
  78005. /**
  78006. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  78007. * @param targetFrameRate defines the target frame rate (60 by default)
  78008. * @returns a SceneOptimizerOptions object
  78009. */
  78010. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  78011. var result = new SceneOptimizerOptions(targetFrameRate);
  78012. var priority = 0;
  78013. result.addOptimization(new MergeMeshesOptimization(priority));
  78014. result.addOptimization(new ShadowsOptimization(priority));
  78015. result.addOptimization(new LensFlaresOptimization(priority));
  78016. // Next priority
  78017. priority++;
  78018. result.addOptimization(new PostProcessesOptimization(priority));
  78019. result.addOptimization(new ParticlesOptimization(priority));
  78020. // Next priority
  78021. priority++;
  78022. result.addOptimization(new TextureOptimization(priority, 1024));
  78023. return result;
  78024. };
  78025. /**
  78026. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  78027. * @param targetFrameRate defines the target frame rate (60 by default)
  78028. * @returns a SceneOptimizerOptions object
  78029. */
  78030. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  78031. var result = new SceneOptimizerOptions(targetFrameRate);
  78032. var priority = 0;
  78033. result.addOptimization(new MergeMeshesOptimization(priority));
  78034. result.addOptimization(new ShadowsOptimization(priority));
  78035. result.addOptimization(new LensFlaresOptimization(priority));
  78036. // Next priority
  78037. priority++;
  78038. result.addOptimization(new PostProcessesOptimization(priority));
  78039. result.addOptimization(new ParticlesOptimization(priority));
  78040. // Next priority
  78041. priority++;
  78042. result.addOptimization(new TextureOptimization(priority, 512));
  78043. // Next priority
  78044. priority++;
  78045. result.addOptimization(new RenderTargetsOptimization(priority));
  78046. // Next priority
  78047. priority++;
  78048. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  78049. return result;
  78050. };
  78051. /**
  78052. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  78053. * @param targetFrameRate defines the target frame rate (60 by default)
  78054. * @returns a SceneOptimizerOptions object
  78055. */
  78056. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  78057. var result = new SceneOptimizerOptions(targetFrameRate);
  78058. var priority = 0;
  78059. result.addOptimization(new MergeMeshesOptimization(priority));
  78060. result.addOptimization(new ShadowsOptimization(priority));
  78061. result.addOptimization(new LensFlaresOptimization(priority));
  78062. // Next priority
  78063. priority++;
  78064. result.addOptimization(new PostProcessesOptimization(priority));
  78065. result.addOptimization(new ParticlesOptimization(priority));
  78066. // Next priority
  78067. priority++;
  78068. result.addOptimization(new TextureOptimization(priority, 256));
  78069. // Next priority
  78070. priority++;
  78071. result.addOptimization(new RenderTargetsOptimization(priority));
  78072. // Next priority
  78073. priority++;
  78074. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  78075. return result;
  78076. };
  78077. return SceneOptimizerOptions;
  78078. }());
  78079. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  78080. /**
  78081. * Class used to run optimizations in order to reach a target frame rate
  78082. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78083. */
  78084. var SceneOptimizer = /** @class */ (function () {
  78085. /**
  78086. * Creates a new SceneOptimizer
  78087. * @param scene defines the scene to work on
  78088. * @param options defines the options to use with the SceneOptimizer
  78089. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  78090. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  78091. */
  78092. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  78093. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  78094. if (improvementMode === void 0) { improvementMode = false; }
  78095. var _this = this;
  78096. this._isRunning = false;
  78097. this._currentPriorityLevel = 0;
  78098. this._targetFrameRate = 60;
  78099. this._trackerDuration = 2000;
  78100. this._currentFrameRate = 0;
  78101. this._improvementMode = false;
  78102. /**
  78103. * Defines an observable called when the optimizer reaches the target frame rate
  78104. */
  78105. this.onSuccessObservable = new BABYLON.Observable();
  78106. /**
  78107. * Defines an observable called when the optimizer enables an optimization
  78108. */
  78109. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  78110. /**
  78111. * Defines an observable called when the optimizer is not able to reach the target frame rate
  78112. */
  78113. this.onFailureObservable = new BABYLON.Observable();
  78114. if (!options) {
  78115. this._options = new SceneOptimizerOptions();
  78116. }
  78117. else {
  78118. this._options = options;
  78119. }
  78120. if (this._options.targetFrameRate) {
  78121. this._targetFrameRate = this._options.targetFrameRate;
  78122. }
  78123. if (this._options.trackerDuration) {
  78124. this._trackerDuration = this._options.trackerDuration;
  78125. }
  78126. if (autoGeneratePriorities) {
  78127. var priority = 0;
  78128. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  78129. var optim = _a[_i];
  78130. optim.priority = priority++;
  78131. }
  78132. }
  78133. this._improvementMode = improvementMode;
  78134. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78135. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  78136. _this._sceneDisposeObserver = null;
  78137. _this.dispose();
  78138. });
  78139. }
  78140. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  78141. /**
  78142. * Gets a boolean indicating if the optimizer is in improvement mode
  78143. */
  78144. get: function () {
  78145. return this._improvementMode;
  78146. },
  78147. enumerable: true,
  78148. configurable: true
  78149. });
  78150. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  78151. /**
  78152. * Gets the current priority level (0 at start)
  78153. */
  78154. get: function () {
  78155. return this._currentPriorityLevel;
  78156. },
  78157. enumerable: true,
  78158. configurable: true
  78159. });
  78160. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  78161. /**
  78162. * Gets the current frame rate checked by the SceneOptimizer
  78163. */
  78164. get: function () {
  78165. return this._currentFrameRate;
  78166. },
  78167. enumerable: true,
  78168. configurable: true
  78169. });
  78170. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  78171. /**
  78172. * Gets or sets the current target frame rate (60 by default)
  78173. */
  78174. get: function () {
  78175. return this._targetFrameRate;
  78176. },
  78177. /**
  78178. * Gets or sets the current target frame rate (60 by default)
  78179. */
  78180. set: function (value) {
  78181. this._targetFrameRate = value;
  78182. },
  78183. enumerable: true,
  78184. configurable: true
  78185. });
  78186. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  78187. /**
  78188. * Gets or sets the current interval between two checks (every 2000ms by default)
  78189. */
  78190. get: function () {
  78191. return this._trackerDuration;
  78192. },
  78193. /**
  78194. * Gets or sets the current interval between two checks (every 2000ms by default)
  78195. */
  78196. set: function (value) {
  78197. this._trackerDuration = value;
  78198. },
  78199. enumerable: true,
  78200. configurable: true
  78201. });
  78202. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  78203. /**
  78204. * Gets the list of active optimizations
  78205. */
  78206. get: function () {
  78207. return this._options.optimizations;
  78208. },
  78209. enumerable: true,
  78210. configurable: true
  78211. });
  78212. /**
  78213. * Stops the current optimizer
  78214. */
  78215. SceneOptimizer.prototype.stop = function () {
  78216. this._isRunning = false;
  78217. };
  78218. /**
  78219. * Reset the optimizer to initial step (current priority level = 0)
  78220. */
  78221. SceneOptimizer.prototype.reset = function () {
  78222. this._currentPriorityLevel = 0;
  78223. };
  78224. /**
  78225. * Start the optimizer. By default it will try to reach a specific framerate
  78226. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  78227. */
  78228. SceneOptimizer.prototype.start = function () {
  78229. var _this = this;
  78230. if (this._isRunning) {
  78231. return;
  78232. }
  78233. this._isRunning = true;
  78234. // Let's wait for the scene to be ready before running our check
  78235. this._scene.executeWhenReady(function () {
  78236. setTimeout(function () {
  78237. _this._checkCurrentState();
  78238. }, _this._trackerDuration);
  78239. });
  78240. };
  78241. SceneOptimizer.prototype._checkCurrentState = function () {
  78242. var _this = this;
  78243. if (!this._isRunning) {
  78244. return;
  78245. }
  78246. var scene = this._scene;
  78247. var options = this._options;
  78248. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  78249. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  78250. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  78251. this._isRunning = false;
  78252. this.onSuccessObservable.notifyObservers(this);
  78253. return;
  78254. }
  78255. // Apply current level of optimizations
  78256. var allDone = true;
  78257. var noOptimizationApplied = true;
  78258. for (var index = 0; index < options.optimizations.length; index++) {
  78259. var optimization = options.optimizations[index];
  78260. if (optimization.priority === this._currentPriorityLevel) {
  78261. noOptimizationApplied = false;
  78262. allDone = allDone && optimization.apply(scene, this);
  78263. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  78264. }
  78265. }
  78266. // If no optimization was applied, this is a failure :(
  78267. if (noOptimizationApplied) {
  78268. this._isRunning = false;
  78269. this.onFailureObservable.notifyObservers(this);
  78270. return;
  78271. }
  78272. // If all optimizations were done, move to next level
  78273. if (allDone) {
  78274. this._currentPriorityLevel++;
  78275. }
  78276. // Let's the system running for a specific amount of time before checking FPS
  78277. scene.executeWhenReady(function () {
  78278. setTimeout(function () {
  78279. _this._checkCurrentState();
  78280. }, _this._trackerDuration);
  78281. });
  78282. };
  78283. /**
  78284. * Release all resources
  78285. */
  78286. SceneOptimizer.prototype.dispose = function () {
  78287. this.stop();
  78288. this.onSuccessObservable.clear();
  78289. this.onFailureObservable.clear();
  78290. this.onNewOptimizationAppliedObservable.clear();
  78291. if (this._sceneDisposeObserver) {
  78292. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  78293. }
  78294. };
  78295. /**
  78296. * Helper function to create a SceneOptimizer with one single line of code
  78297. * @param scene defines the scene to work on
  78298. * @param options defines the options to use with the SceneOptimizer
  78299. * @param onSuccess defines a callback to call on success
  78300. * @param onFailure defines a callback to call on failure
  78301. * @returns the new SceneOptimizer object
  78302. */
  78303. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  78304. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  78305. if (onSuccess) {
  78306. optimizer.onSuccessObservable.add(function () {
  78307. onSuccess();
  78308. });
  78309. }
  78310. if (onFailure) {
  78311. optimizer.onFailureObservable.add(function () {
  78312. onFailure();
  78313. });
  78314. }
  78315. optimizer.start();
  78316. return optimizer;
  78317. };
  78318. return SceneOptimizer;
  78319. }());
  78320. BABYLON.SceneOptimizer = SceneOptimizer;
  78321. })(BABYLON || (BABYLON = {}));
  78322. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  78323. var BABYLON;
  78324. (function (BABYLON) {
  78325. var OutlineRenderer = /** @class */ (function () {
  78326. function OutlineRenderer(scene) {
  78327. this.zOffset = 1;
  78328. this._scene = scene;
  78329. }
  78330. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  78331. var _this = this;
  78332. if (useOverlay === void 0) { useOverlay = false; }
  78333. var scene = this._scene;
  78334. var engine = this._scene.getEngine();
  78335. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78336. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  78337. return;
  78338. }
  78339. var mesh = subMesh.getRenderingMesh();
  78340. var material = subMesh.getMaterial();
  78341. if (!material || !scene.activeCamera) {
  78342. return;
  78343. }
  78344. engine.enableEffect(this._effect);
  78345. // Logarithmic depth
  78346. if (material.useLogarithmicDepth) {
  78347. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  78348. }
  78349. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  78350. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78351. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78352. // Bones
  78353. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78354. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78355. }
  78356. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78357. // Alpha test
  78358. if (material && material.needAlphaTesting()) {
  78359. var alphaTexture = material.getAlphaTestTexture();
  78360. if (alphaTexture) {
  78361. this._effect.setTexture("diffuseSampler", alphaTexture);
  78362. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78363. }
  78364. }
  78365. engine.setZOffset(-this.zOffset);
  78366. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78367. engine.setZOffset(0);
  78368. };
  78369. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78370. var defines = [];
  78371. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78372. var mesh = subMesh.getMesh();
  78373. var material = subMesh.getMaterial();
  78374. if (material) {
  78375. // Alpha test
  78376. if (material.needAlphaTesting()) {
  78377. defines.push("#define ALPHATEST");
  78378. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78379. attribs.push(BABYLON.VertexBuffer.UVKind);
  78380. defines.push("#define UV1");
  78381. }
  78382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78383. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78384. defines.push("#define UV2");
  78385. }
  78386. }
  78387. //Logarithmic depth
  78388. if (material.useLogarithmicDepth) {
  78389. defines.push("#define LOGARITHMICDEPTH");
  78390. }
  78391. }
  78392. // Bones
  78393. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78396. if (mesh.numBoneInfluencers > 4) {
  78397. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78398. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78399. }
  78400. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78401. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78402. }
  78403. else {
  78404. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78405. }
  78406. // Instances
  78407. if (useInstances) {
  78408. defines.push("#define INSTANCES");
  78409. attribs.push("world0");
  78410. attribs.push("world1");
  78411. attribs.push("world2");
  78412. attribs.push("world3");
  78413. }
  78414. // Get correct effect
  78415. var join = defines.join("\n");
  78416. if (this._cachedDefines !== join) {
  78417. this._cachedDefines = join;
  78418. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  78419. }
  78420. return this._effect.isReady();
  78421. };
  78422. return OutlineRenderer;
  78423. }());
  78424. BABYLON.OutlineRenderer = OutlineRenderer;
  78425. })(BABYLON || (BABYLON = {}));
  78426. //# sourceMappingURL=babylon.outlineRenderer.js.map
  78427. var BABYLON;
  78428. (function (BABYLON) {
  78429. var FaceAdjacencies = /** @class */ (function () {
  78430. function FaceAdjacencies() {
  78431. this.edges = new Array();
  78432. this.edgesConnectedCount = 0;
  78433. }
  78434. return FaceAdjacencies;
  78435. }());
  78436. var EdgesRenderer = /** @class */ (function () {
  78437. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  78438. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  78439. if (epsilon === void 0) { epsilon = 0.95; }
  78440. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  78441. this.edgesWidthScalerForOrthographic = 1000.0;
  78442. this.edgesWidthScalerForPerspective = 50.0;
  78443. this._linesPositions = new Array();
  78444. this._linesNormals = new Array();
  78445. this._linesIndices = new Array();
  78446. this._buffers = {};
  78447. this._checkVerticesInsteadOfIndices = false;
  78448. this._source = source;
  78449. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  78450. this._epsilon = epsilon;
  78451. this._prepareRessources();
  78452. this._generateEdgesLines();
  78453. }
  78454. EdgesRenderer.prototype._prepareRessources = function () {
  78455. if (this._lineShader) {
  78456. return;
  78457. }
  78458. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  78459. attributes: ["position", "normal"],
  78460. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  78461. });
  78462. this._lineShader.disableDepthWrite = true;
  78463. this._lineShader.backFaceCulling = false;
  78464. };
  78465. EdgesRenderer.prototype._rebuild = function () {
  78466. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78467. if (buffer) {
  78468. buffer._rebuild();
  78469. }
  78470. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78471. if (buffer) {
  78472. buffer._rebuild();
  78473. }
  78474. var scene = this._source.getScene();
  78475. var engine = scene.getEngine();
  78476. this._ib = engine.createIndexBuffer(this._linesIndices);
  78477. };
  78478. EdgesRenderer.prototype.dispose = function () {
  78479. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78480. if (buffer) {
  78481. buffer.dispose();
  78482. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  78483. }
  78484. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78485. if (buffer) {
  78486. buffer.dispose();
  78487. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  78488. }
  78489. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  78490. this._lineShader.dispose();
  78491. };
  78492. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  78493. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  78494. return 0;
  78495. }
  78496. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  78497. return 1;
  78498. }
  78499. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  78500. return 2;
  78501. }
  78502. return -1;
  78503. };
  78504. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  78505. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  78506. return 0;
  78507. }
  78508. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  78509. return 1;
  78510. }
  78511. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  78512. return 2;
  78513. }
  78514. return -1;
  78515. };
  78516. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  78517. var needToCreateLine;
  78518. if (edge === undefined) {
  78519. needToCreateLine = true;
  78520. }
  78521. else {
  78522. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  78523. needToCreateLine = dotProduct < this._epsilon;
  78524. }
  78525. if (needToCreateLine) {
  78526. var offset = this._linesPositions.length / 3;
  78527. var normal = p0.subtract(p1);
  78528. normal.normalize();
  78529. // Positions
  78530. this._linesPositions.push(p0.x);
  78531. this._linesPositions.push(p0.y);
  78532. this._linesPositions.push(p0.z);
  78533. this._linesPositions.push(p0.x);
  78534. this._linesPositions.push(p0.y);
  78535. this._linesPositions.push(p0.z);
  78536. this._linesPositions.push(p1.x);
  78537. this._linesPositions.push(p1.y);
  78538. this._linesPositions.push(p1.z);
  78539. this._linesPositions.push(p1.x);
  78540. this._linesPositions.push(p1.y);
  78541. this._linesPositions.push(p1.z);
  78542. // Normals
  78543. this._linesNormals.push(p1.x);
  78544. this._linesNormals.push(p1.y);
  78545. this._linesNormals.push(p1.z);
  78546. this._linesNormals.push(-1);
  78547. this._linesNormals.push(p1.x);
  78548. this._linesNormals.push(p1.y);
  78549. this._linesNormals.push(p1.z);
  78550. this._linesNormals.push(1);
  78551. this._linesNormals.push(p0.x);
  78552. this._linesNormals.push(p0.y);
  78553. this._linesNormals.push(p0.z);
  78554. this._linesNormals.push(-1);
  78555. this._linesNormals.push(p0.x);
  78556. this._linesNormals.push(p0.y);
  78557. this._linesNormals.push(p0.z);
  78558. this._linesNormals.push(1);
  78559. // Indices
  78560. this._linesIndices.push(offset);
  78561. this._linesIndices.push(offset + 1);
  78562. this._linesIndices.push(offset + 2);
  78563. this._linesIndices.push(offset);
  78564. this._linesIndices.push(offset + 2);
  78565. this._linesIndices.push(offset + 3);
  78566. }
  78567. };
  78568. EdgesRenderer.prototype._generateEdgesLines = function () {
  78569. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78570. var indices = this._source.getIndices();
  78571. if (!indices || !positions) {
  78572. return;
  78573. }
  78574. // First let's find adjacencies
  78575. var adjacencies = new Array();
  78576. var faceNormals = new Array();
  78577. var index;
  78578. var faceAdjacencies;
  78579. // Prepare faces
  78580. for (index = 0; index < indices.length; index += 3) {
  78581. faceAdjacencies = new FaceAdjacencies();
  78582. var p0Index = indices[index];
  78583. var p1Index = indices[index + 1];
  78584. var p2Index = indices[index + 2];
  78585. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  78586. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  78587. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  78588. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  78589. faceNormal.normalize();
  78590. faceNormals.push(faceNormal);
  78591. adjacencies.push(faceAdjacencies);
  78592. }
  78593. // Scan
  78594. for (index = 0; index < adjacencies.length; index++) {
  78595. faceAdjacencies = adjacencies[index];
  78596. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  78597. var otherFaceAdjacencies = adjacencies[otherIndex];
  78598. if (faceAdjacencies.edgesConnectedCount === 3) {
  78599. break;
  78600. }
  78601. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  78602. continue;
  78603. }
  78604. var otherP0 = indices[otherIndex * 3];
  78605. var otherP1 = indices[otherIndex * 3 + 1];
  78606. var otherP2 = indices[otherIndex * 3 + 2];
  78607. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  78608. var otherEdgeIndex = 0;
  78609. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  78610. continue;
  78611. }
  78612. switch (edgeIndex) {
  78613. case 0:
  78614. if (this._checkVerticesInsteadOfIndices) {
  78615. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78616. }
  78617. else {
  78618. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  78619. }
  78620. break;
  78621. case 1:
  78622. if (this._checkVerticesInsteadOfIndices) {
  78623. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78624. }
  78625. else {
  78626. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  78627. }
  78628. break;
  78629. case 2:
  78630. if (this._checkVerticesInsteadOfIndices) {
  78631. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78632. }
  78633. else {
  78634. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  78635. }
  78636. break;
  78637. }
  78638. if (otherEdgeIndex === -1) {
  78639. continue;
  78640. }
  78641. faceAdjacencies.edges[edgeIndex] = otherIndex;
  78642. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  78643. faceAdjacencies.edgesConnectedCount++;
  78644. otherFaceAdjacencies.edgesConnectedCount++;
  78645. if (faceAdjacencies.edgesConnectedCount === 3) {
  78646. break;
  78647. }
  78648. }
  78649. }
  78650. }
  78651. // Create lines
  78652. for (index = 0; index < adjacencies.length; index++) {
  78653. // 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
  78654. var current = adjacencies[index];
  78655. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  78656. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  78657. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  78658. }
  78659. // Merge into a single mesh
  78660. var engine = this._source.getScene().getEngine();
  78661. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  78662. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  78663. this._ib = engine.createIndexBuffer(this._linesIndices);
  78664. this._indicesCount = this._linesIndices.length;
  78665. };
  78666. EdgesRenderer.prototype.render = function () {
  78667. var scene = this._source.getScene();
  78668. if (!this._lineShader.isReady() || !scene.activeCamera) {
  78669. return;
  78670. }
  78671. var engine = scene.getEngine();
  78672. this._lineShader._preBind();
  78673. // VBOs
  78674. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  78675. scene.resetCachedMaterial();
  78676. this._lineShader.setColor4("color", this._source.edgesColor);
  78677. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  78678. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  78679. }
  78680. else {
  78681. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  78682. }
  78683. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  78684. this._lineShader.bind(this._source.getWorldMatrix());
  78685. // Draw order
  78686. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  78687. this._lineShader.unbind();
  78688. engine.setDepthWrite(true);
  78689. };
  78690. return EdgesRenderer;
  78691. }());
  78692. BABYLON.EdgesRenderer = EdgesRenderer;
  78693. })(BABYLON || (BABYLON = {}));
  78694. //# sourceMappingURL=babylon.edgesRenderer.js.map
  78695. var BABYLON;
  78696. (function (BABYLON) {
  78697. /**
  78698. * Special Glow Blur post process only blurring the alpha channel
  78699. * It enforces keeping the most luminous color in the color channel.
  78700. */
  78701. var GlowBlurPostProcess = /** @class */ (function (_super) {
  78702. __extends(GlowBlurPostProcess, _super);
  78703. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  78704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78705. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  78706. _this.direction = direction;
  78707. _this.kernel = kernel;
  78708. _this.onApplyObservable.add(function (effect) {
  78709. effect.setFloat2("screenSize", _this.width, _this.height);
  78710. effect.setVector2("direction", _this.direction);
  78711. effect.setFloat("blurWidth", _this.kernel);
  78712. });
  78713. return _this;
  78714. }
  78715. return GlowBlurPostProcess;
  78716. }(BABYLON.PostProcess));
  78717. /**
  78718. * The highlight layer Helps adding a glow effect around a mesh.
  78719. *
  78720. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  78721. * glowy meshes to your scene.
  78722. *
  78723. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  78724. */
  78725. var HighlightLayer = /** @class */ (function () {
  78726. /**
  78727. * Instantiates a new highlight Layer and references it to the scene..
  78728. * @param name The name of the layer
  78729. * @param scene The scene to use the layer in
  78730. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  78731. */
  78732. function HighlightLayer(name, scene, options) {
  78733. this.name = name;
  78734. this._vertexBuffers = {};
  78735. this._mainTextureDesiredSize = { width: 0, height: 0 };
  78736. this._meshes = {};
  78737. this._maxSize = 0;
  78738. this._shouldRender = false;
  78739. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  78740. this._excludedMeshes = {};
  78741. /**
  78742. * Specifies whether or not the inner glow is ACTIVE in the layer.
  78743. */
  78744. this.innerGlow = true;
  78745. /**
  78746. * Specifies whether or not the outer glow is ACTIVE in the layer.
  78747. */
  78748. this.outerGlow = true;
  78749. /**
  78750. * Specifies wether the highlight layer is enabled or not.
  78751. */
  78752. this.isEnabled = true;
  78753. /**
  78754. * An event triggered when the highlight layer has been disposed.
  78755. * @type {BABYLON.Observable}
  78756. */
  78757. this.onDisposeObservable = new BABYLON.Observable();
  78758. /**
  78759. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  78760. * @type {BABYLON.Observable}
  78761. */
  78762. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  78763. /**
  78764. * An event triggered when the highlight layer is being blurred.
  78765. * @type {BABYLON.Observable}
  78766. */
  78767. this.onBeforeBlurObservable = new BABYLON.Observable();
  78768. /**
  78769. * An event triggered when the highlight layer has been blurred.
  78770. * @type {BABYLON.Observable}
  78771. */
  78772. this.onAfterBlurObservable = new BABYLON.Observable();
  78773. /**
  78774. * An event triggered when the glowing blurred texture is being merged in the scene.
  78775. * @type {BABYLON.Observable}
  78776. */
  78777. this.onBeforeComposeObservable = new BABYLON.Observable();
  78778. /**
  78779. * An event triggered when the glowing blurred texture has been merged in the scene.
  78780. * @type {BABYLON.Observable}
  78781. */
  78782. this.onAfterComposeObservable = new BABYLON.Observable();
  78783. /**
  78784. * An event triggered when the highlight layer changes its size.
  78785. * @type {BABYLON.Observable}
  78786. */
  78787. this.onSizeChangedObservable = new BABYLON.Observable();
  78788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78789. var engine = scene.getEngine();
  78790. this._engine = engine;
  78791. this._maxSize = this._engine.getCaps().maxTextureSize;
  78792. this._scene.highlightLayers.push(this);
  78793. // Warn on stencil.
  78794. if (!this._engine.isStencilEnable) {
  78795. 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 }");
  78796. }
  78797. // Adapt options
  78798. this._options = options || {
  78799. mainTextureRatio: 0.5,
  78800. blurTextureSizeRatio: 0.5,
  78801. blurHorizontalSize: 1.0,
  78802. blurVerticalSize: 1.0,
  78803. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  78804. camera: null
  78805. };
  78806. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  78807. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  78808. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  78809. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  78810. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  78811. // VBO
  78812. var vertices = [];
  78813. vertices.push(1, 1);
  78814. vertices.push(-1, 1);
  78815. vertices.push(-1, -1);
  78816. vertices.push(1, -1);
  78817. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78818. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78819. this._createIndexBuffer();
  78820. // Effect
  78821. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  78822. // Render target
  78823. this.setMainTextureSize();
  78824. // Create Textures and post processes
  78825. this.createTextureAndPostProcesses();
  78826. }
  78827. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  78828. /**
  78829. * Gets the horizontal size of the blur.
  78830. */
  78831. get: function () {
  78832. return this._horizontalBlurPostprocess.kernel;
  78833. },
  78834. /**
  78835. * Specifies the horizontal size of the blur.
  78836. */
  78837. set: function (value) {
  78838. this._horizontalBlurPostprocess.kernel = value;
  78839. },
  78840. enumerable: true,
  78841. configurable: true
  78842. });
  78843. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  78844. /**
  78845. * Gets the vertical size of the blur.
  78846. */
  78847. get: function () {
  78848. return this._verticalBlurPostprocess.kernel;
  78849. },
  78850. /**
  78851. * Specifies the vertical size of the blur.
  78852. */
  78853. set: function (value) {
  78854. this._verticalBlurPostprocess.kernel = value;
  78855. },
  78856. enumerable: true,
  78857. configurable: true
  78858. });
  78859. Object.defineProperty(HighlightLayer.prototype, "camera", {
  78860. /**
  78861. * Gets the camera attached to the layer.
  78862. */
  78863. get: function () {
  78864. return this._options.camera;
  78865. },
  78866. enumerable: true,
  78867. configurable: true
  78868. });
  78869. HighlightLayer.prototype._createIndexBuffer = function () {
  78870. var engine = this._scene.getEngine();
  78871. // Indices
  78872. var indices = [];
  78873. indices.push(0);
  78874. indices.push(1);
  78875. indices.push(2);
  78876. indices.push(0);
  78877. indices.push(2);
  78878. indices.push(3);
  78879. this._indexBuffer = engine.createIndexBuffer(indices);
  78880. };
  78881. HighlightLayer.prototype._rebuild = function () {
  78882. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78883. if (vb) {
  78884. vb._rebuild();
  78885. }
  78886. this._createIndexBuffer();
  78887. };
  78888. /**
  78889. * Creates the render target textures and post processes used in the highlight layer.
  78890. */
  78891. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  78892. var _this = this;
  78893. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  78894. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  78895. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  78896. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  78897. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  78898. width: this._mainTextureDesiredSize.width,
  78899. height: this._mainTextureDesiredSize.height
  78900. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78901. this._mainTexture.activeCamera = this._options.camera;
  78902. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78903. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78904. this._mainTexture.anisotropicFilteringLevel = 1;
  78905. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78906. this._mainTexture.renderParticles = false;
  78907. this._mainTexture.renderList = null;
  78908. this._mainTexture.ignoreCameraViewport = true;
  78909. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  78910. width: blurTextureWidth,
  78911. height: blurTextureHeight
  78912. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78913. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78914. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78915. this._blurTexture.anisotropicFilteringLevel = 16;
  78916. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78917. this._blurTexture.renderParticles = false;
  78918. this._blurTexture.ignoreCameraViewport = true;
  78919. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78920. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  78921. effect.setTexture("textureSampler", _this._mainTexture);
  78922. });
  78923. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  78924. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78925. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78926. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78927. });
  78928. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78929. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78930. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78931. });
  78932. }
  78933. else {
  78934. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78935. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78936. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78937. });
  78938. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78939. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78940. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78941. });
  78942. }
  78943. this._mainTexture.onAfterUnbindObservable.add(function () {
  78944. _this.onBeforeBlurObservable.notifyObservers(_this);
  78945. var internalTexture = _this._blurTexture.getInternalTexture();
  78946. if (internalTexture) {
  78947. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  78948. }
  78949. _this.onAfterBlurObservable.notifyObservers(_this);
  78950. });
  78951. // Custom render function
  78952. var renderSubMesh = function (subMesh) {
  78953. if (!_this._meshes) {
  78954. return;
  78955. }
  78956. var material = subMesh.getMaterial();
  78957. var mesh = subMesh.getRenderingMesh();
  78958. var scene = _this._scene;
  78959. var engine = scene.getEngine();
  78960. if (!material) {
  78961. return;
  78962. }
  78963. // Do not block in blend mode.
  78964. if (material.needAlphaBlendingForMesh(mesh)) {
  78965. return;
  78966. }
  78967. // Culling
  78968. engine.setState(material.backFaceCulling);
  78969. // Managing instances
  78970. var batch = mesh._getInstancesRenderList(subMesh._id);
  78971. if (batch.mustReturn) {
  78972. return;
  78973. }
  78974. // Excluded Mesh
  78975. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  78976. return;
  78977. }
  78978. ;
  78979. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78980. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  78981. var emissiveTexture = null;
  78982. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  78983. emissiveTexture = material.emissiveTexture;
  78984. }
  78985. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  78986. engine.enableEffect(_this._glowMapGenerationEffect);
  78987. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  78988. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  78989. if (highlightLayerMesh) {
  78990. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  78991. }
  78992. else {
  78993. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  78994. }
  78995. // Alpha test
  78996. if (material && material.needAlphaTesting()) {
  78997. var alphaTexture = material.getAlphaTestTexture();
  78998. if (alphaTexture) {
  78999. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  79000. var textureMatrix = alphaTexture.getTextureMatrix();
  79001. if (textureMatrix) {
  79002. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  79003. }
  79004. }
  79005. }
  79006. // Glow emissive only
  79007. if (emissiveTexture) {
  79008. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  79009. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  79010. }
  79011. // Bones
  79012. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79013. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79014. }
  79015. // Draw
  79016. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  79017. }
  79018. else {
  79019. // Need to reset refresh rate of the shadowMap
  79020. _this._mainTexture.resetRefreshCounter();
  79021. }
  79022. };
  79023. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79024. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  79025. var index;
  79026. var engine = _this._scene.getEngine();
  79027. if (depthOnlySubMeshes.length) {
  79028. engine.setColorWrite(false);
  79029. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79030. renderSubMesh(depthOnlySubMeshes.data[index]);
  79031. }
  79032. engine.setColorWrite(true);
  79033. }
  79034. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79035. renderSubMesh(opaqueSubMeshes.data[index]);
  79036. }
  79037. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79038. renderSubMesh(alphaTestSubMeshes.data[index]);
  79039. }
  79040. for (index = 0; index < transparentSubMeshes.length; index++) {
  79041. renderSubMesh(transparentSubMeshes.data[index]);
  79042. }
  79043. };
  79044. this._mainTexture.onClearObservable.add(function (engine) {
  79045. engine.clear(HighlightLayer.neutralColor, true, true, true);
  79046. });
  79047. };
  79048. /**
  79049. * Checks for the readiness of the element composing the layer.
  79050. * @param subMesh the mesh to check for
  79051. * @param useInstances specify wether or not to use instances to render the mesh
  79052. * @param emissiveTexture the associated emissive texture used to generate the glow
  79053. * @return true if ready otherwise, false
  79054. */
  79055. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  79056. var material = subMesh.getMaterial();
  79057. var mesh = subMesh.getRenderingMesh();
  79058. if (!material || !mesh || !this._meshes) {
  79059. return false;
  79060. }
  79061. var emissiveTexture = null;
  79062. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  79063. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79064. emissiveTexture = material.emissiveTexture;
  79065. }
  79066. return this._isReady(subMesh, useInstances, emissiveTexture);
  79067. };
  79068. /**
  79069. * Checks for the readiness of the element composing the layer.
  79070. * @param subMesh the mesh to check for
  79071. * @param useInstances specify wether or not to use instances to render the mesh
  79072. * @param emissiveTexture the associated emissive texture used to generate the glow
  79073. * @return true if ready otherwise, false
  79074. */
  79075. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  79076. var material = subMesh.getMaterial();
  79077. if (!material) {
  79078. return false;
  79079. }
  79080. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  79081. return false;
  79082. }
  79083. var defines = [];
  79084. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79085. var mesh = subMesh.getMesh();
  79086. var uv1 = false;
  79087. var uv2 = false;
  79088. // Alpha test
  79089. if (material && material.needAlphaTesting()) {
  79090. var alphaTexture = material.getAlphaTestTexture();
  79091. if (alphaTexture) {
  79092. defines.push("#define ALPHATEST");
  79093. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79094. alphaTexture.coordinatesIndex === 1) {
  79095. defines.push("#define DIFFUSEUV2");
  79096. uv2 = true;
  79097. }
  79098. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79099. defines.push("#define DIFFUSEUV1");
  79100. uv1 = true;
  79101. }
  79102. }
  79103. }
  79104. // Emissive
  79105. if (emissiveTexture) {
  79106. defines.push("#define EMISSIVE");
  79107. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79108. emissiveTexture.coordinatesIndex === 1) {
  79109. defines.push("#define EMISSIVEUV2");
  79110. uv2 = true;
  79111. }
  79112. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79113. defines.push("#define EMISSIVEUV1");
  79114. uv1 = true;
  79115. }
  79116. }
  79117. if (uv1) {
  79118. attribs.push(BABYLON.VertexBuffer.UVKind);
  79119. defines.push("#define UV1");
  79120. }
  79121. if (uv2) {
  79122. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79123. defines.push("#define UV2");
  79124. }
  79125. // Bones
  79126. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79127. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79128. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79129. if (mesh.numBoneInfluencers > 4) {
  79130. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79131. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79132. }
  79133. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79134. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79135. }
  79136. else {
  79137. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79138. }
  79139. // Instances
  79140. if (useInstances) {
  79141. defines.push("#define INSTANCES");
  79142. attribs.push("world0");
  79143. attribs.push("world1");
  79144. attribs.push("world2");
  79145. attribs.push("world3");
  79146. }
  79147. // Get correct effect
  79148. var join = defines.join("\n");
  79149. if (this._cachedDefines !== join) {
  79150. this._cachedDefines = join;
  79151. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  79152. }
  79153. return this._glowMapGenerationEffect.isReady();
  79154. };
  79155. /**
  79156. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  79157. */
  79158. HighlightLayer.prototype.render = function () {
  79159. var currentEffect = this._glowMapMergeEffect;
  79160. // Check
  79161. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  79162. return;
  79163. var engine = this._scene.getEngine();
  79164. this.onBeforeComposeObservable.notifyObservers(this);
  79165. // Render
  79166. engine.enableEffect(currentEffect);
  79167. engine.setState(false);
  79168. // Cache
  79169. var previousStencilBuffer = engine.getStencilBuffer();
  79170. var previousStencilFunction = engine.getStencilFunction();
  79171. var previousStencilMask = engine.getStencilMask();
  79172. var previousStencilOperationPass = engine.getStencilOperationPass();
  79173. var previousStencilOperationFail = engine.getStencilOperationFail();
  79174. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  79175. var previousAlphaMode = engine.getAlphaMode();
  79176. // Texture
  79177. currentEffect.setTexture("textureSampler", this._blurTexture);
  79178. // VBOs
  79179. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  79180. // Stencil operations
  79181. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  79182. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  79183. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  79184. // Draw order
  79185. engine.setAlphaMode(this._options.alphaBlendingMode);
  79186. engine.setStencilMask(0x00);
  79187. engine.setStencilBuffer(true);
  79188. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  79189. if (this.outerGlow) {
  79190. currentEffect.setFloat("offset", 0);
  79191. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  79192. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79193. }
  79194. if (this.innerGlow) {
  79195. currentEffect.setFloat("offset", 1);
  79196. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  79197. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79198. }
  79199. // Restore Cache
  79200. engine.setStencilFunction(previousStencilFunction);
  79201. engine.setStencilMask(previousStencilMask);
  79202. engine.setAlphaMode(previousAlphaMode);
  79203. engine.setStencilBuffer(previousStencilBuffer);
  79204. engine.setStencilOperationPass(previousStencilOperationPass);
  79205. engine.setStencilOperationFail(previousStencilOperationFail);
  79206. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  79207. engine._stencilState.reset();
  79208. this.onAfterComposeObservable.notifyObservers(this);
  79209. // Handle size changes.
  79210. var size = this._mainTexture.getSize();
  79211. this.setMainTextureSize();
  79212. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  79213. // Recreate RTT and post processes on size change.
  79214. this.onSizeChangedObservable.notifyObservers(this);
  79215. this.disposeTextureAndPostProcesses();
  79216. this.createTextureAndPostProcesses();
  79217. }
  79218. };
  79219. /**
  79220. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  79221. * @param mesh The mesh to exclude from the highlight layer
  79222. */
  79223. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  79224. if (!this._excludedMeshes) {
  79225. return;
  79226. }
  79227. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79228. if (!meshExcluded) {
  79229. this._excludedMeshes[mesh.uniqueId] = {
  79230. mesh: mesh,
  79231. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  79232. mesh.getEngine().setStencilBuffer(false);
  79233. }),
  79234. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  79235. mesh.getEngine().setStencilBuffer(true);
  79236. }),
  79237. };
  79238. }
  79239. };
  79240. /**
  79241. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  79242. * @param mesh The mesh to highlight
  79243. */
  79244. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  79245. if (!this._excludedMeshes) {
  79246. return;
  79247. }
  79248. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79249. if (meshExcluded) {
  79250. if (meshExcluded.beforeRender) {
  79251. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  79252. }
  79253. if (meshExcluded.afterRender) {
  79254. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  79255. }
  79256. }
  79257. this._excludedMeshes[mesh.uniqueId] = null;
  79258. };
  79259. /**
  79260. * Determine if a given mesh will be highlighted by the current HighlightLayer
  79261. * @param mesh mesh to test
  79262. * @returns true if the mesh will be highlighted by the current HighlightLayer
  79263. */
  79264. HighlightLayer.prototype.hasMesh = function (mesh) {
  79265. if (!this._meshes) {
  79266. return false;
  79267. }
  79268. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  79269. };
  79270. /**
  79271. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  79272. * @param mesh The mesh to highlight
  79273. * @param color The color of the highlight
  79274. * @param glowEmissiveOnly Extract the glow from the emissive texture
  79275. */
  79276. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  79277. var _this = this;
  79278. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  79279. if (!this._meshes) {
  79280. return;
  79281. }
  79282. var meshHighlight = this._meshes[mesh.uniqueId];
  79283. if (meshHighlight) {
  79284. meshHighlight.color = color;
  79285. }
  79286. else {
  79287. this._meshes[mesh.uniqueId] = {
  79288. mesh: mesh,
  79289. color: color,
  79290. // Lambda required for capture due to Observable this context
  79291. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  79292. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79293. _this.defaultStencilReference(mesh);
  79294. }
  79295. else {
  79296. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  79297. }
  79298. }),
  79299. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  79300. glowEmissiveOnly: glowEmissiveOnly
  79301. };
  79302. }
  79303. this._shouldRender = true;
  79304. };
  79305. /**
  79306. * Remove a mesh from the highlight layer in order to make it stop glowing.
  79307. * @param mesh The mesh to highlight
  79308. */
  79309. HighlightLayer.prototype.removeMesh = function (mesh) {
  79310. if (!this._meshes) {
  79311. return;
  79312. }
  79313. var meshHighlight = this._meshes[mesh.uniqueId];
  79314. if (meshHighlight) {
  79315. if (meshHighlight.observerHighlight) {
  79316. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79317. }
  79318. if (meshHighlight.observerDefault) {
  79319. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79320. }
  79321. delete this._meshes[mesh.uniqueId];
  79322. }
  79323. this._shouldRender = false;
  79324. for (var meshHighlightToCheck in this._meshes) {
  79325. if (this._meshes[meshHighlightToCheck]) {
  79326. this._shouldRender = true;
  79327. break;
  79328. }
  79329. }
  79330. };
  79331. /**
  79332. * Returns true if the layer contains information to display, otherwise false.
  79333. */
  79334. HighlightLayer.prototype.shouldRender = function () {
  79335. return this.isEnabled && this._shouldRender;
  79336. };
  79337. /**
  79338. * Sets the main texture desired size which is the closest power of two
  79339. * of the engine canvas size.
  79340. */
  79341. HighlightLayer.prototype.setMainTextureSize = function () {
  79342. if (this._options.mainTextureFixedSize) {
  79343. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  79344. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  79345. }
  79346. else {
  79347. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  79348. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  79349. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  79350. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79351. }
  79352. };
  79353. /**
  79354. * Force the stencil to the normal expected value for none glowing parts
  79355. */
  79356. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79357. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79358. };
  79359. /**
  79360. * Dispose only the render target textures and post process.
  79361. */
  79362. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79363. this._blurTexture.dispose();
  79364. this._mainTexture.dispose();
  79365. this._downSamplePostprocess.dispose();
  79366. this._horizontalBlurPostprocess.dispose();
  79367. this._verticalBlurPostprocess.dispose();
  79368. };
  79369. /**
  79370. * Dispose the highlight layer and free resources.
  79371. */
  79372. HighlightLayer.prototype.dispose = function () {
  79373. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79374. if (vertexBuffer) {
  79375. vertexBuffer.dispose();
  79376. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79377. }
  79378. if (this._indexBuffer) {
  79379. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79380. this._indexBuffer = null;
  79381. }
  79382. // Clean textures and post processes
  79383. this.disposeTextureAndPostProcesses();
  79384. if (this._meshes) {
  79385. // Clean mesh references
  79386. for (var id in this._meshes) {
  79387. var meshHighlight = this._meshes[id];
  79388. if (meshHighlight && meshHighlight.mesh) {
  79389. if (meshHighlight.observerHighlight) {
  79390. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79391. }
  79392. if (meshHighlight.observerDefault) {
  79393. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79394. }
  79395. }
  79396. }
  79397. this._meshes = null;
  79398. }
  79399. if (this._excludedMeshes) {
  79400. for (var id in this._excludedMeshes) {
  79401. var meshHighlight = this._excludedMeshes[id];
  79402. if (meshHighlight) {
  79403. if (meshHighlight.beforeRender) {
  79404. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  79405. }
  79406. if (meshHighlight.afterRender) {
  79407. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  79408. }
  79409. }
  79410. }
  79411. this._excludedMeshes = null;
  79412. }
  79413. // Remove from scene
  79414. var index = this._scene.highlightLayers.indexOf(this, 0);
  79415. if (index > -1) {
  79416. this._scene.highlightLayers.splice(index, 1);
  79417. }
  79418. // Callback
  79419. this.onDisposeObservable.notifyObservers(this);
  79420. this.onDisposeObservable.clear();
  79421. this.onBeforeRenderMainTextureObservable.clear();
  79422. this.onBeforeBlurObservable.clear();
  79423. this.onBeforeComposeObservable.clear();
  79424. this.onAfterComposeObservable.clear();
  79425. this.onSizeChangedObservable.clear();
  79426. };
  79427. /**
  79428. * The neutral color used during the preparation of the glow effect.
  79429. * This is black by default as the blend operation is a blend operation.
  79430. */
  79431. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  79432. /**
  79433. * Stencil value used for glowing meshes.
  79434. */
  79435. HighlightLayer.glowingMeshStencilReference = 0x02;
  79436. /**
  79437. * Stencil value used for the other meshes in the scene.
  79438. */
  79439. HighlightLayer.normalMeshStencilReference = 0x01;
  79440. return HighlightLayer;
  79441. }());
  79442. BABYLON.HighlightLayer = HighlightLayer;
  79443. })(BABYLON || (BABYLON = {}));
  79444. //# sourceMappingURL=babylon.highlightlayer.js.map
  79445. var BABYLON;
  79446. (function (BABYLON) {
  79447. /**
  79448. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  79449. */
  79450. var AssetTaskState;
  79451. (function (AssetTaskState) {
  79452. /**
  79453. * Initialization
  79454. */
  79455. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  79456. /**
  79457. * Running
  79458. */
  79459. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  79460. /**
  79461. * Done
  79462. */
  79463. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  79464. /**
  79465. * Error
  79466. */
  79467. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  79468. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  79469. /**
  79470. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  79471. */
  79472. var AbstractAssetTask = /** @class */ (function () {
  79473. /**
  79474. * Creates a new {BABYLON.AssetsManager}
  79475. * @param name defines the name of the task
  79476. */
  79477. function AbstractAssetTask(
  79478. /**
  79479. * Task name
  79480. */ name) {
  79481. this.name = name;
  79482. this._isCompleted = false;
  79483. this._taskState = AssetTaskState.INIT;
  79484. }
  79485. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  79486. /**
  79487. * Get if the task is completed
  79488. */
  79489. get: function () {
  79490. return this._isCompleted;
  79491. },
  79492. enumerable: true,
  79493. configurable: true
  79494. });
  79495. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  79496. /**
  79497. * Gets the current state of the task
  79498. */
  79499. get: function () {
  79500. return this._taskState;
  79501. },
  79502. enumerable: true,
  79503. configurable: true
  79504. });
  79505. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  79506. /**
  79507. * Gets the current error object (if task is in error)
  79508. */
  79509. get: function () {
  79510. return this._errorObject;
  79511. },
  79512. enumerable: true,
  79513. configurable: true
  79514. });
  79515. /**
  79516. * Internal only
  79517. * @ignore
  79518. */
  79519. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  79520. if (this._errorObject) {
  79521. return;
  79522. }
  79523. this._errorObject = {
  79524. message: message,
  79525. exception: exception
  79526. };
  79527. };
  79528. /**
  79529. * Execute the current task
  79530. * @param scene defines the scene where you want your assets to be loaded
  79531. * @param onSuccess is a callback called when the task is successfully executed
  79532. * @param onError is a callback called if an error occurs
  79533. */
  79534. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79535. var _this = this;
  79536. this._taskState = AssetTaskState.RUNNING;
  79537. this.runTask(scene, function () {
  79538. _this.onDoneCallback(onSuccess, onError);
  79539. }, function (msg, exception) {
  79540. _this.onErrorCallback(onError, msg, exception);
  79541. });
  79542. };
  79543. /**
  79544. * Execute the current task
  79545. * @param scene defines the scene where you want your assets to be loaded
  79546. * @param onSuccess is a callback called when the task is successfully executed
  79547. * @param onError is a callback called if an error occurs
  79548. */
  79549. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79550. throw new Error("runTask is not implemented");
  79551. };
  79552. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  79553. this._taskState = AssetTaskState.ERROR;
  79554. this._errorObject = {
  79555. message: message,
  79556. exception: exception
  79557. };
  79558. if (this.onError) {
  79559. this.onError(this, message, exception);
  79560. }
  79561. onError();
  79562. };
  79563. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  79564. try {
  79565. this._taskState = AssetTaskState.DONE;
  79566. this._isCompleted = true;
  79567. if (this.onSuccess) {
  79568. this.onSuccess(this);
  79569. }
  79570. onSuccess();
  79571. }
  79572. catch (e) {
  79573. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  79574. }
  79575. };
  79576. return AbstractAssetTask;
  79577. }());
  79578. BABYLON.AbstractAssetTask = AbstractAssetTask;
  79579. /**
  79580. * Class used to share progress information about assets loading
  79581. */
  79582. var AssetsProgressEvent = /** @class */ (function () {
  79583. /**
  79584. * Creates a {BABYLON.AssetsProgressEvent}
  79585. * @param remainingCount defines the number of remaining tasks to process
  79586. * @param totalCount defines the total number of tasks
  79587. * @param task defines the task that was just processed
  79588. */
  79589. function AssetsProgressEvent(remainingCount, totalCount, task) {
  79590. this.remainingCount = remainingCount;
  79591. this.totalCount = totalCount;
  79592. this.task = task;
  79593. }
  79594. return AssetsProgressEvent;
  79595. }());
  79596. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  79597. /**
  79598. * Define a task used by {BABYLON.AssetsManager} to load meshes
  79599. */
  79600. var MeshAssetTask = /** @class */ (function (_super) {
  79601. __extends(MeshAssetTask, _super);
  79602. /**
  79603. * Creates a new {BABYLON.MeshAssetTask}
  79604. * @param name defines the name of the task
  79605. * @param meshesNames defines the list of mesh's names you want to load
  79606. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  79607. * @param sceneFilename defines the filename of the scene to load from
  79608. */
  79609. function MeshAssetTask(
  79610. /**
  79611. * Defines the name of the task
  79612. */
  79613. name,
  79614. /**
  79615. * Defines the list of mesh's names you want to load
  79616. */
  79617. meshesNames,
  79618. /**
  79619. * Defines the root url to use as a base to load your meshes and associated resources
  79620. */
  79621. rootUrl,
  79622. /**
  79623. * Defines the filename of the scene to load from
  79624. */
  79625. sceneFilename) {
  79626. var _this = _super.call(this, name) || this;
  79627. _this.name = name;
  79628. _this.meshesNames = meshesNames;
  79629. _this.rootUrl = rootUrl;
  79630. _this.sceneFilename = sceneFilename;
  79631. return _this;
  79632. }
  79633. /**
  79634. * Execute the current task
  79635. * @param scene defines the scene where you want your assets to be loaded
  79636. * @param onSuccess is a callback called when the task is successfully executed
  79637. * @param onError is a callback called if an error occurs
  79638. */
  79639. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79640. var _this = this;
  79641. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  79642. _this.loadedMeshes = meshes;
  79643. _this.loadedParticleSystems = particleSystems;
  79644. _this.loadedSkeletons = skeletons;
  79645. onSuccess();
  79646. }, null, function (scene, message, exception) {
  79647. onError(message, exception);
  79648. });
  79649. };
  79650. return MeshAssetTask;
  79651. }(AbstractAssetTask));
  79652. BABYLON.MeshAssetTask = MeshAssetTask;
  79653. /**
  79654. * Define a task used by {BABYLON.AssetsManager} to load text content
  79655. */
  79656. var TextFileAssetTask = /** @class */ (function (_super) {
  79657. __extends(TextFileAssetTask, _super);
  79658. /**
  79659. * Creates a new TextFileAssetTask object
  79660. * @param name defines the name of the task
  79661. * @param url defines the location of the file to load
  79662. */
  79663. function TextFileAssetTask(
  79664. /**
  79665. * Defines the name of the task
  79666. */
  79667. name,
  79668. /**
  79669. * Defines the location of the file to load
  79670. */
  79671. url) {
  79672. var _this = _super.call(this, name) || this;
  79673. _this.name = name;
  79674. _this.url = url;
  79675. return _this;
  79676. }
  79677. /**
  79678. * Execute the current task
  79679. * @param scene defines the scene where you want your assets to be loaded
  79680. * @param onSuccess is a callback called when the task is successfully executed
  79681. * @param onError is a callback called if an error occurs
  79682. */
  79683. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79684. var _this = this;
  79685. scene._loadFile(this.url, function (data) {
  79686. _this.text = data;
  79687. onSuccess();
  79688. }, undefined, false, true, function (request, exception) {
  79689. if (request) {
  79690. onError(request.status + " " + request.statusText, exception);
  79691. }
  79692. });
  79693. };
  79694. return TextFileAssetTask;
  79695. }(AbstractAssetTask));
  79696. BABYLON.TextFileAssetTask = TextFileAssetTask;
  79697. /**
  79698. * Define a task used by {BABYLON.AssetsManager} to load binary data
  79699. */
  79700. var BinaryFileAssetTask = /** @class */ (function (_super) {
  79701. __extends(BinaryFileAssetTask, _super);
  79702. /**
  79703. * Creates a new BinaryFileAssetTask object
  79704. * @param name defines the name of the new task
  79705. * @param url defines the location of the file to load
  79706. */
  79707. function BinaryFileAssetTask(
  79708. /**
  79709. * Defines the name of the task
  79710. */
  79711. name,
  79712. /**
  79713. * Defines the location of the file to load
  79714. */
  79715. url) {
  79716. var _this = _super.call(this, name) || this;
  79717. _this.name = name;
  79718. _this.url = url;
  79719. return _this;
  79720. }
  79721. /**
  79722. * Execute the current task
  79723. * @param scene defines the scene where you want your assets to be loaded
  79724. * @param onSuccess is a callback called when the task is successfully executed
  79725. * @param onError is a callback called if an error occurs
  79726. */
  79727. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79728. var _this = this;
  79729. scene._loadFile(this.url, function (data) {
  79730. _this.data = data;
  79731. onSuccess();
  79732. }, undefined, true, true, function (request, exception) {
  79733. if (request) {
  79734. onError(request.status + " " + request.statusText, exception);
  79735. }
  79736. });
  79737. };
  79738. return BinaryFileAssetTask;
  79739. }(AbstractAssetTask));
  79740. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  79741. /**
  79742. * Define a task used by {BABYLON.AssetsManager} to load images
  79743. */
  79744. var ImageAssetTask = /** @class */ (function (_super) {
  79745. __extends(ImageAssetTask, _super);
  79746. /**
  79747. * Creates a new ImageAssetTask
  79748. * @param name defines the name of the task
  79749. * @param url defines the location of the image to load
  79750. */
  79751. function ImageAssetTask(
  79752. /**
  79753. * Defines the name of the task
  79754. */
  79755. name,
  79756. /**
  79757. * Defines the location of the image to load
  79758. */
  79759. url) {
  79760. var _this = _super.call(this, name) || this;
  79761. _this.name = name;
  79762. _this.url = url;
  79763. return _this;
  79764. }
  79765. /**
  79766. * Execute the current task
  79767. * @param scene defines the scene where you want your assets to be loaded
  79768. * @param onSuccess is a callback called when the task is successfully executed
  79769. * @param onError is a callback called if an error occurs
  79770. */
  79771. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79772. var _this = this;
  79773. var img = new Image();
  79774. BABYLON.Tools.SetCorsBehavior(this.url, img);
  79775. img.onload = function () {
  79776. _this.image = img;
  79777. onSuccess();
  79778. };
  79779. img.onerror = function (err) {
  79780. onError("Error loading image", err);
  79781. };
  79782. img.src = this.url;
  79783. };
  79784. return ImageAssetTask;
  79785. }(AbstractAssetTask));
  79786. BABYLON.ImageAssetTask = ImageAssetTask;
  79787. /**
  79788. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  79789. */
  79790. var TextureAssetTask = /** @class */ (function (_super) {
  79791. __extends(TextureAssetTask, _super);
  79792. /**
  79793. * Creates a new TextureAssetTask object
  79794. * @param name defines the name of the task
  79795. * @param url defines the location of the file to load
  79796. * @param noMipmap defines if mipmap should not be generated (default is false)
  79797. * @param invertY defines if texture must be inverted on Y axis (default is false)
  79798. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79799. */
  79800. function TextureAssetTask(
  79801. /**
  79802. * Defines the name of the task
  79803. */
  79804. name,
  79805. /**
  79806. * Defines the location of the file to load
  79807. */
  79808. url,
  79809. /**
  79810. * Defines if mipmap should not be generated (default is false)
  79811. */
  79812. noMipmap,
  79813. /**
  79814. * Defines if texture must be inverted on Y axis (default is false)
  79815. */
  79816. invertY,
  79817. /**
  79818. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79819. */
  79820. samplingMode) {
  79821. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79822. var _this = _super.call(this, name) || this;
  79823. _this.name = name;
  79824. _this.url = url;
  79825. _this.noMipmap = noMipmap;
  79826. _this.invertY = invertY;
  79827. _this.samplingMode = samplingMode;
  79828. return _this;
  79829. }
  79830. /**
  79831. * Execute the current task
  79832. * @param scene defines the scene where you want your assets to be loaded
  79833. * @param onSuccess is a callback called when the task is successfully executed
  79834. * @param onError is a callback called if an error occurs
  79835. */
  79836. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79837. var onload = function () {
  79838. onSuccess();
  79839. };
  79840. var onerror = function (message, exception) {
  79841. onError(message, exception);
  79842. };
  79843. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  79844. };
  79845. return TextureAssetTask;
  79846. }(AbstractAssetTask));
  79847. BABYLON.TextureAssetTask = TextureAssetTask;
  79848. /**
  79849. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  79850. */
  79851. var CubeTextureAssetTask = /** @class */ (function (_super) {
  79852. __extends(CubeTextureAssetTask, _super);
  79853. /**
  79854. * Creates a new CubeTextureAssetTask
  79855. * @param name defines the name of the task
  79856. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79857. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79858. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79859. * @param files defines the explicit list of files (undefined by default)
  79860. */
  79861. function CubeTextureAssetTask(
  79862. /**
  79863. * Defines the name of the task
  79864. */
  79865. name,
  79866. /**
  79867. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79868. */
  79869. url,
  79870. /**
  79871. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79872. */
  79873. extensions,
  79874. /**
  79875. * Defines if mipmaps should not be generated (default is false)
  79876. */
  79877. noMipmap,
  79878. /**
  79879. * Defines the explicit list of files (undefined by default)
  79880. */
  79881. files) {
  79882. var _this = _super.call(this, name) || this;
  79883. _this.name = name;
  79884. _this.url = url;
  79885. _this.extensions = extensions;
  79886. _this.noMipmap = noMipmap;
  79887. _this.files = files;
  79888. return _this;
  79889. }
  79890. /**
  79891. * Execute the current task
  79892. * @param scene defines the scene where you want your assets to be loaded
  79893. * @param onSuccess is a callback called when the task is successfully executed
  79894. * @param onError is a callback called if an error occurs
  79895. */
  79896. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79897. var onload = function () {
  79898. onSuccess();
  79899. };
  79900. var onerror = function (message, exception) {
  79901. onError(message, exception);
  79902. };
  79903. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  79904. };
  79905. return CubeTextureAssetTask;
  79906. }(AbstractAssetTask));
  79907. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  79908. /**
  79909. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  79910. */
  79911. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  79912. __extends(HDRCubeTextureAssetTask, _super);
  79913. /**
  79914. * Creates a new HDRCubeTextureAssetTask object
  79915. * @param name defines the name of the task
  79916. * @param url defines the location of the file to load
  79917. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  79918. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79919. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79920. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  79921. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79922. */
  79923. function HDRCubeTextureAssetTask(
  79924. /**
  79925. * Defines the name of the task
  79926. */
  79927. name,
  79928. /**
  79929. * Defines the location of the file to load
  79930. */
  79931. url,
  79932. /**
  79933. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  79934. */
  79935. size,
  79936. /**
  79937. * Defines if mipmaps should not be generated (default is false)
  79938. */
  79939. noMipmap,
  79940. /**
  79941. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79942. */
  79943. generateHarmonics,
  79944. /**
  79945. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  79946. */
  79947. useInGammaSpace,
  79948. /**
  79949. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79950. */
  79951. usePMREMGenerator) {
  79952. if (noMipmap === void 0) { noMipmap = false; }
  79953. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79954. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79955. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79956. var _this = _super.call(this, name) || this;
  79957. _this.name = name;
  79958. _this.url = url;
  79959. _this.size = size;
  79960. _this.noMipmap = noMipmap;
  79961. _this.generateHarmonics = generateHarmonics;
  79962. _this.useInGammaSpace = useInGammaSpace;
  79963. _this.usePMREMGenerator = usePMREMGenerator;
  79964. return _this;
  79965. }
  79966. /**
  79967. * Execute the current task
  79968. * @param scene defines the scene where you want your assets to be loaded
  79969. * @param onSuccess is a callback called when the task is successfully executed
  79970. * @param onError is a callback called if an error occurs
  79971. */
  79972. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79973. var onload = function () {
  79974. onSuccess();
  79975. };
  79976. var onerror = function (message, exception) {
  79977. onError(message, exception);
  79978. };
  79979. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  79980. };
  79981. return HDRCubeTextureAssetTask;
  79982. }(AbstractAssetTask));
  79983. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  79984. /**
  79985. * This class can be used to easily import assets into a scene
  79986. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  79987. */
  79988. var AssetsManager = /** @class */ (function () {
  79989. /**
  79990. * Creates a new AssetsManager
  79991. * @param scene defines the scene to work on
  79992. */
  79993. function AssetsManager(scene) {
  79994. this._isLoading = false;
  79995. this._tasks = new Array();
  79996. this._waitingTasksCount = 0;
  79997. this._totalTasksCount = 0;
  79998. /**
  79999. * Observable called when all tasks are processed
  80000. */
  80001. this.onTaskSuccessObservable = new BABYLON.Observable();
  80002. /**
  80003. * Observable called when a task had an error
  80004. */
  80005. this.onTaskErrorObservable = new BABYLON.Observable();
  80006. /**
  80007. * Observable called when a task is successful
  80008. */
  80009. this.onTasksDoneObservable = new BABYLON.Observable();
  80010. /**
  80011. * Observable called when a task is done (whatever the result is)
  80012. */
  80013. this.onProgressObservable = new BABYLON.Observable();
  80014. /**
  80015. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  80016. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  80017. */
  80018. this.useDefaultLoadingScreen = true;
  80019. this._scene = scene;
  80020. }
  80021. /**
  80022. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  80023. * @param taskName defines the name of the new task
  80024. * @param meshesNames defines the name of meshes to load
  80025. * @param rootUrl defines the root url to use to locate files
  80026. * @param sceneFilename defines the filename of the scene file
  80027. * @returns a new {BABYLON.MeshAssetTask} object
  80028. */
  80029. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  80030. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  80031. this._tasks.push(task);
  80032. return task;
  80033. };
  80034. /**
  80035. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  80036. * @param taskName defines the name of the new task
  80037. * @param url defines the url of the file to load
  80038. * @returns a new {BABYLON.TextFileAssetTask} object
  80039. */
  80040. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  80041. var task = new TextFileAssetTask(taskName, url);
  80042. this._tasks.push(task);
  80043. return task;
  80044. };
  80045. /**
  80046. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  80047. * @param taskName defines the name of the new task
  80048. * @param url defines the url of the file to load
  80049. * @returns a new {BABYLON.BinaryFileAssetTask} object
  80050. */
  80051. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  80052. var task = new BinaryFileAssetTask(taskName, url);
  80053. this._tasks.push(task);
  80054. return task;
  80055. };
  80056. /**
  80057. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  80058. * @param taskName defines the name of the new task
  80059. * @param url defines the url of the file to load
  80060. * @returns a new {BABYLON.ImageAssetTask} object
  80061. */
  80062. AssetsManager.prototype.addImageTask = function (taskName, url) {
  80063. var task = new ImageAssetTask(taskName, url);
  80064. this._tasks.push(task);
  80065. return task;
  80066. };
  80067. /**
  80068. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  80069. * @param taskName defines the name of the new task
  80070. * @param url defines the url of the file to load
  80071. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80072. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  80073. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  80074. * @returns a new {BABYLON.TextureAssetTask} object
  80075. */
  80076. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  80077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80078. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  80079. this._tasks.push(task);
  80080. return task;
  80081. };
  80082. /**
  80083. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  80084. * @param taskName defines the name of the new task
  80085. * @param url defines the url of the file to load
  80086. * @param extensions defines the extension to use to load the cube map (can be null)
  80087. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80088. * @param files defines the list of files to load (can be null)
  80089. * @returns a new {BABYLON.CubeTextureAssetTask} object
  80090. */
  80091. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  80092. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  80093. this._tasks.push(task);
  80094. return task;
  80095. };
  80096. /**
  80097. *
  80098. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  80099. * @param taskName defines the name of the new task
  80100. * @param url defines the url of the file to load
  80101. * @param size defines the size you want for the cubemap (can be null)
  80102. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80103. * @param generateHarmonics defines if you want to automatically generate (true by default)
  80104. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  80105. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  80106. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  80107. */
  80108. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  80109. if (noMipmap === void 0) { noMipmap = false; }
  80110. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80111. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80112. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80113. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  80114. this._tasks.push(task);
  80115. return task;
  80116. };
  80117. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  80118. var _this = this;
  80119. this._waitingTasksCount--;
  80120. try {
  80121. if (task.taskState === AssetTaskState.DONE) {
  80122. // Let's remove successfull tasks
  80123. BABYLON.Tools.SetImmediate(function () {
  80124. var index = _this._tasks.indexOf(task);
  80125. if (index > -1) {
  80126. _this._tasks.splice(index, 1);
  80127. }
  80128. });
  80129. }
  80130. if (this.onProgress) {
  80131. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  80132. }
  80133. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  80134. }
  80135. catch (e) {
  80136. BABYLON.Tools.Error("Error running progress callbacks.");
  80137. console.log(e);
  80138. }
  80139. if (this._waitingTasksCount === 0) {
  80140. try {
  80141. if (this.onFinish) {
  80142. this.onFinish(this._tasks);
  80143. }
  80144. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80145. }
  80146. catch (e) {
  80147. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  80148. console.log(e);
  80149. }
  80150. this._isLoading = false;
  80151. this._scene.getEngine().hideLoadingUI();
  80152. }
  80153. };
  80154. AssetsManager.prototype._runTask = function (task) {
  80155. var _this = this;
  80156. var done = function () {
  80157. try {
  80158. if (_this.onTaskSuccess) {
  80159. _this.onTaskSuccess(task);
  80160. }
  80161. _this.onTaskSuccessObservable.notifyObservers(task);
  80162. _this._decreaseWaitingTasksCount(task);
  80163. }
  80164. catch (e) {
  80165. error("Error executing task success callbacks", e);
  80166. }
  80167. };
  80168. var error = function (message, exception) {
  80169. task._setErrorObject(message, exception);
  80170. if (_this.onTaskError) {
  80171. _this.onTaskError(task);
  80172. }
  80173. _this.onTaskErrorObservable.notifyObservers(task);
  80174. _this._decreaseWaitingTasksCount(task);
  80175. };
  80176. task.run(this._scene, done, error);
  80177. };
  80178. /**
  80179. * Reset the {BABYLON.AssetsManager} and remove all tasks
  80180. * @return the current instance of the {BABYLON.AssetsManager}
  80181. */
  80182. AssetsManager.prototype.reset = function () {
  80183. this._isLoading = false;
  80184. this._tasks = new Array();
  80185. return this;
  80186. };
  80187. /**
  80188. * Start the loading process
  80189. * @return the current instance of the {BABYLON.AssetsManager}
  80190. */
  80191. AssetsManager.prototype.load = function () {
  80192. if (this._isLoading) {
  80193. return this;
  80194. }
  80195. this._isLoading = true;
  80196. this._waitingTasksCount = this._tasks.length;
  80197. this._totalTasksCount = this._tasks.length;
  80198. if (this._waitingTasksCount === 0) {
  80199. if (this.onFinish) {
  80200. this.onFinish(this._tasks);
  80201. }
  80202. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80203. return this;
  80204. }
  80205. if (this.useDefaultLoadingScreen) {
  80206. this._scene.getEngine().displayLoadingUI();
  80207. }
  80208. for (var index = 0; index < this._tasks.length; index++) {
  80209. var task = this._tasks[index];
  80210. this._runTask(task);
  80211. }
  80212. return this;
  80213. };
  80214. return AssetsManager;
  80215. }());
  80216. BABYLON.AssetsManager = AssetsManager;
  80217. })(BABYLON || (BABYLON = {}));
  80218. //# sourceMappingURL=babylon.assetsManager.js.map
  80219. var BABYLON;
  80220. (function (BABYLON) {
  80221. var serializedGeometries = [];
  80222. var serializeGeometry = function (geometry, serializationGeometries) {
  80223. if (serializedGeometries[geometry.id]) {
  80224. return;
  80225. }
  80226. if (geometry.doNotSerialize) {
  80227. return;
  80228. }
  80229. if (geometry instanceof BABYLON.BoxGeometry) {
  80230. serializationGeometries.boxes.push(geometry.serialize());
  80231. }
  80232. else if (geometry instanceof BABYLON.SphereGeometry) {
  80233. serializationGeometries.spheres.push(geometry.serialize());
  80234. }
  80235. else if (geometry instanceof BABYLON.CylinderGeometry) {
  80236. serializationGeometries.cylinders.push(geometry.serialize());
  80237. }
  80238. else if (geometry instanceof BABYLON.TorusGeometry) {
  80239. serializationGeometries.toruses.push(geometry.serialize());
  80240. }
  80241. else if (geometry instanceof BABYLON.GroundGeometry) {
  80242. serializationGeometries.grounds.push(geometry.serialize());
  80243. }
  80244. else if (geometry instanceof BABYLON.Plane) {
  80245. serializationGeometries.planes.push(geometry.serialize());
  80246. }
  80247. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  80248. serializationGeometries.torusKnots.push(geometry.serialize());
  80249. }
  80250. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  80251. throw new Error("Unknown primitive type");
  80252. }
  80253. else {
  80254. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  80255. }
  80256. serializedGeometries[geometry.id] = true;
  80257. };
  80258. var serializeMesh = function (mesh, serializationScene) {
  80259. var serializationObject = {};
  80260. // Geometry
  80261. var geometry = mesh._geometry;
  80262. if (geometry) {
  80263. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  80264. // 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
  80265. serializeGeometry(geometry, serializationScene.geometries);
  80266. }
  80267. }
  80268. // Custom
  80269. if (mesh.serialize) {
  80270. mesh.serialize(serializationObject);
  80271. }
  80272. return serializationObject;
  80273. };
  80274. var finalizeSingleMesh = function (mesh, serializationObject) {
  80275. //only works if the mesh is already loaded
  80276. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80277. //serialize material
  80278. if (mesh.material) {
  80279. if (mesh.material instanceof BABYLON.StandardMaterial) {
  80280. serializationObject.materials = serializationObject.materials || [];
  80281. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80282. serializationObject.materials.push(mesh.material.serialize());
  80283. }
  80284. }
  80285. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  80286. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  80287. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80288. serializationObject.multiMaterials.push(mesh.material.serialize());
  80289. }
  80290. }
  80291. }
  80292. //serialize geometry
  80293. var geometry = mesh._geometry;
  80294. if (geometry) {
  80295. if (!serializationObject.geometries) {
  80296. serializationObject.geometries = {};
  80297. serializationObject.geometries.boxes = [];
  80298. serializationObject.geometries.spheres = [];
  80299. serializationObject.geometries.cylinders = [];
  80300. serializationObject.geometries.toruses = [];
  80301. serializationObject.geometries.grounds = [];
  80302. serializationObject.geometries.planes = [];
  80303. serializationObject.geometries.torusKnots = [];
  80304. serializationObject.geometries.vertexData = [];
  80305. }
  80306. serializeGeometry(geometry, serializationObject.geometries);
  80307. }
  80308. // Skeletons
  80309. if (mesh.skeleton) {
  80310. serializationObject.skeletons = serializationObject.skeletons || [];
  80311. serializationObject.skeletons.push(mesh.skeleton.serialize());
  80312. }
  80313. //serialize the actual mesh
  80314. serializationObject.meshes = serializationObject.meshes || [];
  80315. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80316. }
  80317. };
  80318. var SceneSerializer = /** @class */ (function () {
  80319. function SceneSerializer() {
  80320. }
  80321. SceneSerializer.ClearCache = function () {
  80322. serializedGeometries = [];
  80323. };
  80324. SceneSerializer.Serialize = function (scene) {
  80325. var serializationObject = {};
  80326. SceneSerializer.ClearCache();
  80327. // Scene
  80328. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  80329. serializationObject.autoClear = scene.autoClear;
  80330. serializationObject.clearColor = scene.clearColor.asArray();
  80331. serializationObject.ambientColor = scene.ambientColor.asArray();
  80332. serializationObject.gravity = scene.gravity.asArray();
  80333. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  80334. serializationObject.workerCollisions = scene.workerCollisions;
  80335. // Fog
  80336. if (scene.fogMode && scene.fogMode !== 0) {
  80337. serializationObject.fogMode = scene.fogMode;
  80338. serializationObject.fogColor = scene.fogColor.asArray();
  80339. serializationObject.fogStart = scene.fogStart;
  80340. serializationObject.fogEnd = scene.fogEnd;
  80341. serializationObject.fogDensity = scene.fogDensity;
  80342. }
  80343. //Physics
  80344. if (scene.isPhysicsEnabled()) {
  80345. var physicEngine = scene.getPhysicsEngine();
  80346. if (physicEngine) {
  80347. serializationObject.physicsEnabled = true;
  80348. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  80349. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  80350. }
  80351. }
  80352. // Metadata
  80353. if (scene.metadata) {
  80354. serializationObject.metadata = scene.metadata;
  80355. }
  80356. // Morph targets
  80357. serializationObject.morphTargetManagers = [];
  80358. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80359. var abstractMesh = _a[_i];
  80360. var manager = abstractMesh.morphTargetManager;
  80361. if (manager) {
  80362. serializationObject.morphTargetManagers.push(manager.serialize());
  80363. }
  80364. }
  80365. // Lights
  80366. serializationObject.lights = [];
  80367. var index;
  80368. var light;
  80369. for (index = 0; index < scene.lights.length; index++) {
  80370. light = scene.lights[index];
  80371. if (!light.doNotSerialize) {
  80372. serializationObject.lights.push(light.serialize());
  80373. }
  80374. }
  80375. // Cameras
  80376. serializationObject.cameras = [];
  80377. for (index = 0; index < scene.cameras.length; index++) {
  80378. var camera = scene.cameras[index];
  80379. if (!camera.doNotSerialize) {
  80380. serializationObject.cameras.push(camera.serialize());
  80381. }
  80382. }
  80383. if (scene.activeCamera) {
  80384. serializationObject.activeCameraID = scene.activeCamera.id;
  80385. }
  80386. // Animations
  80387. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80388. // Materials
  80389. serializationObject.materials = [];
  80390. serializationObject.multiMaterials = [];
  80391. var material;
  80392. for (index = 0; index < scene.materials.length; index++) {
  80393. material = scene.materials[index];
  80394. if (!material.doNotSerialize) {
  80395. serializationObject.materials.push(material.serialize());
  80396. }
  80397. }
  80398. // MultiMaterials
  80399. serializationObject.multiMaterials = [];
  80400. for (index = 0; index < scene.multiMaterials.length; index++) {
  80401. var multiMaterial = scene.multiMaterials[index];
  80402. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80403. }
  80404. // Environment texture
  80405. if (scene.environmentTexture) {
  80406. serializationObject.environmentTexture = scene.environmentTexture.name;
  80407. }
  80408. // Skeletons
  80409. serializationObject.skeletons = [];
  80410. for (index = 0; index < scene.skeletons.length; index++) {
  80411. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  80412. }
  80413. // Transform nodes
  80414. serializationObject.transformNodes = [];
  80415. for (index = 0; index < scene.transformNodes.length; index++) {
  80416. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  80417. }
  80418. // Geometries
  80419. serializationObject.geometries = {};
  80420. serializationObject.geometries.boxes = [];
  80421. serializationObject.geometries.spheres = [];
  80422. serializationObject.geometries.cylinders = [];
  80423. serializationObject.geometries.toruses = [];
  80424. serializationObject.geometries.grounds = [];
  80425. serializationObject.geometries.planes = [];
  80426. serializationObject.geometries.torusKnots = [];
  80427. serializationObject.geometries.vertexData = [];
  80428. serializedGeometries = [];
  80429. var geometries = scene.getGeometries();
  80430. for (index = 0; index < geometries.length; index++) {
  80431. var geometry = geometries[index];
  80432. if (geometry.isReady()) {
  80433. serializeGeometry(geometry, serializationObject.geometries);
  80434. }
  80435. }
  80436. // Meshes
  80437. serializationObject.meshes = [];
  80438. for (index = 0; index < scene.meshes.length; index++) {
  80439. var abstractMesh = scene.meshes[index];
  80440. if (abstractMesh instanceof BABYLON.Mesh) {
  80441. var mesh = abstractMesh;
  80442. if (!mesh.doNotSerialize) {
  80443. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80444. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80445. }
  80446. }
  80447. }
  80448. }
  80449. // Particles Systems
  80450. serializationObject.particleSystems = [];
  80451. for (index = 0; index < scene.particleSystems.length; index++) {
  80452. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  80453. }
  80454. // Lens flares
  80455. serializationObject.lensFlareSystems = [];
  80456. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  80457. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  80458. }
  80459. // Shadows
  80460. serializationObject.shadowGenerators = [];
  80461. for (index = 0; index < scene.lights.length; index++) {
  80462. light = scene.lights[index];
  80463. var shadowGenerator = light.getShadowGenerator();
  80464. if (shadowGenerator) {
  80465. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  80466. }
  80467. }
  80468. // Action Manager
  80469. if (scene.actionManager) {
  80470. serializationObject.actions = scene.actionManager.serialize("scene");
  80471. }
  80472. // Audio
  80473. serializationObject.sounds = [];
  80474. for (index = 0; index < scene.soundTracks.length; index++) {
  80475. var soundtrack = scene.soundTracks[index];
  80476. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  80477. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  80478. }
  80479. }
  80480. return serializationObject;
  80481. };
  80482. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  80483. if (withParents === void 0) { withParents = false; }
  80484. if (withChildren === void 0) { withChildren = false; }
  80485. var serializationObject = {};
  80486. SceneSerializer.ClearCache();
  80487. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  80488. if (withParents || withChildren) {
  80489. //deliberate for loop! not for each, appended should be processed as well.
  80490. for (var i = 0; i < toSerialize.length; ++i) {
  80491. if (withChildren) {
  80492. toSerialize[i].getDescendants().forEach(function (node) {
  80493. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  80494. toSerialize.push(node);
  80495. }
  80496. });
  80497. }
  80498. //make sure the array doesn't contain the object already
  80499. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  80500. toSerialize.push(toSerialize[i].parent);
  80501. }
  80502. }
  80503. }
  80504. toSerialize.forEach(function (mesh) {
  80505. finalizeSingleMesh(mesh, serializationObject);
  80506. });
  80507. return serializationObject;
  80508. };
  80509. return SceneSerializer;
  80510. }());
  80511. BABYLON.SceneSerializer = SceneSerializer;
  80512. })(BABYLON || (BABYLON = {}));
  80513. //# sourceMappingURL=babylon.sceneSerializer.js.map
  80514. var BABYLON;
  80515. (function (BABYLON) {
  80516. var ReflectionProbe = /** @class */ (function () {
  80517. function ReflectionProbe(name, size, scene, generateMipMaps) {
  80518. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80519. var _this = this;
  80520. this.name = name;
  80521. this._viewMatrix = BABYLON.Matrix.Identity();
  80522. this._target = BABYLON.Vector3.Zero();
  80523. this._add = BABYLON.Vector3.Zero();
  80524. this.invertYAxis = false;
  80525. this.position = BABYLON.Vector3.Zero();
  80526. this._scene = scene;
  80527. this._scene.reflectionProbes.push(this);
  80528. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  80529. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  80530. switch (faceIndex) {
  80531. case 0:
  80532. _this._add.copyFromFloats(1, 0, 0);
  80533. break;
  80534. case 1:
  80535. _this._add.copyFromFloats(-1, 0, 0);
  80536. break;
  80537. case 2:
  80538. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  80539. break;
  80540. case 3:
  80541. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  80542. break;
  80543. case 4:
  80544. _this._add.copyFromFloats(0, 0, 1);
  80545. break;
  80546. case 5:
  80547. _this._add.copyFromFloats(0, 0, -1);
  80548. break;
  80549. }
  80550. if (_this._attachedMesh) {
  80551. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  80552. }
  80553. _this.position.addToRef(_this._add, _this._target);
  80554. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  80555. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  80556. scene._forcedViewPosition = _this.position;
  80557. });
  80558. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  80559. scene._forcedViewPosition = null;
  80560. scene.updateTransformMatrix(true);
  80561. });
  80562. if (scene.activeCamera) {
  80563. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80564. }
  80565. }
  80566. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  80567. get: function () {
  80568. return this._renderTargetTexture.samples;
  80569. },
  80570. set: function (value) {
  80571. this._renderTargetTexture.samples = value;
  80572. },
  80573. enumerable: true,
  80574. configurable: true
  80575. });
  80576. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  80577. get: function () {
  80578. return this._renderTargetTexture.refreshRate;
  80579. },
  80580. set: function (value) {
  80581. this._renderTargetTexture.refreshRate = value;
  80582. },
  80583. enumerable: true,
  80584. configurable: true
  80585. });
  80586. ReflectionProbe.prototype.getScene = function () {
  80587. return this._scene;
  80588. };
  80589. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  80590. get: function () {
  80591. return this._renderTargetTexture;
  80592. },
  80593. enumerable: true,
  80594. configurable: true
  80595. });
  80596. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  80597. get: function () {
  80598. return this._renderTargetTexture.renderList;
  80599. },
  80600. enumerable: true,
  80601. configurable: true
  80602. });
  80603. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  80604. this._attachedMesh = mesh;
  80605. };
  80606. /**
  80607. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  80608. *
  80609. * @param renderingGroupId The rendering group id corresponding to its index
  80610. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  80611. */
  80612. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  80613. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  80614. };
  80615. ReflectionProbe.prototype.dispose = function () {
  80616. var index = this._scene.reflectionProbes.indexOf(this);
  80617. if (index !== -1) {
  80618. // Remove from the scene if found
  80619. this._scene.reflectionProbes.splice(index, 1);
  80620. }
  80621. if (this._renderTargetTexture) {
  80622. this._renderTargetTexture.dispose();
  80623. this._renderTargetTexture = null;
  80624. }
  80625. };
  80626. return ReflectionProbe;
  80627. }());
  80628. BABYLON.ReflectionProbe = ReflectionProbe;
  80629. })(BABYLON || (BABYLON = {}));
  80630. //# sourceMappingURL=babylon.reflectionProbe.js.map
  80631. var BABYLON;
  80632. (function (BABYLON) {
  80633. var Layer = /** @class */ (function () {
  80634. function Layer(name, imgUrl, scene, isBackground, color) {
  80635. this.name = name;
  80636. this.scale = new BABYLON.Vector2(1, 1);
  80637. this.offset = new BABYLON.Vector2(0, 0);
  80638. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  80639. this.layerMask = 0x0FFFFFFF;
  80640. this._vertexBuffers = {};
  80641. // Events
  80642. /**
  80643. * An event triggered when the layer is disposed.
  80644. * @type {BABYLON.Observable}
  80645. */
  80646. this.onDisposeObservable = new BABYLON.Observable();
  80647. /**
  80648. * An event triggered before rendering the scene
  80649. * @type {BABYLON.Observable}
  80650. */
  80651. this.onBeforeRenderObservable = new BABYLON.Observable();
  80652. /**
  80653. * An event triggered after rendering the scene
  80654. * @type {BABYLON.Observable}
  80655. */
  80656. this.onAfterRenderObservable = new BABYLON.Observable();
  80657. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  80658. this.isBackground = isBackground === undefined ? true : isBackground;
  80659. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  80660. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  80661. this._scene.layers.push(this);
  80662. var engine = this._scene.getEngine();
  80663. // VBO
  80664. var vertices = [];
  80665. vertices.push(1, 1);
  80666. vertices.push(-1, 1);
  80667. vertices.push(-1, -1);
  80668. vertices.push(1, -1);
  80669. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80670. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80671. this._createIndexBuffer();
  80672. // Effects
  80673. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  80674. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  80675. }
  80676. Object.defineProperty(Layer.prototype, "onDispose", {
  80677. set: function (callback) {
  80678. if (this._onDisposeObserver) {
  80679. this.onDisposeObservable.remove(this._onDisposeObserver);
  80680. }
  80681. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  80682. },
  80683. enumerable: true,
  80684. configurable: true
  80685. });
  80686. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  80687. set: function (callback) {
  80688. if (this._onBeforeRenderObserver) {
  80689. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  80690. }
  80691. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  80692. },
  80693. enumerable: true,
  80694. configurable: true
  80695. });
  80696. Object.defineProperty(Layer.prototype, "onAfterRender", {
  80697. set: function (callback) {
  80698. if (this._onAfterRenderObserver) {
  80699. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80700. }
  80701. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  80702. },
  80703. enumerable: true,
  80704. configurable: true
  80705. });
  80706. Layer.prototype._createIndexBuffer = function () {
  80707. var engine = this._scene.getEngine();
  80708. // Indices
  80709. var indices = [];
  80710. indices.push(0);
  80711. indices.push(1);
  80712. indices.push(2);
  80713. indices.push(0);
  80714. indices.push(2);
  80715. indices.push(3);
  80716. this._indexBuffer = engine.createIndexBuffer(indices);
  80717. };
  80718. Layer.prototype._rebuild = function () {
  80719. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80720. if (vb) {
  80721. vb._rebuild();
  80722. }
  80723. this._createIndexBuffer();
  80724. };
  80725. Layer.prototype.render = function () {
  80726. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  80727. // Check
  80728. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  80729. return;
  80730. var engine = this._scene.getEngine();
  80731. this.onBeforeRenderObservable.notifyObservers(this);
  80732. // Render
  80733. engine.enableEffect(currentEffect);
  80734. engine.setState(false);
  80735. // Texture
  80736. currentEffect.setTexture("textureSampler", this.texture);
  80737. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  80738. // Color
  80739. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  80740. // Scale / offset
  80741. currentEffect.setVector2("offset", this.offset);
  80742. currentEffect.setVector2("scale", this.scale);
  80743. // VBOs
  80744. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80745. // Draw order
  80746. if (!this.alphaTest) {
  80747. engine.setAlphaMode(this.alphaBlendingMode);
  80748. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80749. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80750. }
  80751. else {
  80752. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80753. }
  80754. this.onAfterRenderObservable.notifyObservers(this);
  80755. };
  80756. Layer.prototype.dispose = function () {
  80757. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80758. if (vertexBuffer) {
  80759. vertexBuffer.dispose();
  80760. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80761. }
  80762. if (this._indexBuffer) {
  80763. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80764. this._indexBuffer = null;
  80765. }
  80766. if (this.texture) {
  80767. this.texture.dispose();
  80768. this.texture = null;
  80769. }
  80770. // Remove from scene
  80771. var index = this._scene.layers.indexOf(this);
  80772. this._scene.layers.splice(index, 1);
  80773. // Callback
  80774. this.onDisposeObservable.notifyObservers(this);
  80775. this.onDisposeObservable.clear();
  80776. this.onAfterRenderObservable.clear();
  80777. this.onBeforeRenderObservable.clear();
  80778. };
  80779. return Layer;
  80780. }());
  80781. BABYLON.Layer = Layer;
  80782. })(BABYLON || (BABYLON = {}));
  80783. //# sourceMappingURL=babylon.layer.js.map
  80784. var BABYLON;
  80785. (function (BABYLON) {
  80786. var TextureTools = /** @class */ (function () {
  80787. function TextureTools() {
  80788. }
  80789. /**
  80790. * Uses the GPU to create a copy texture rescaled at a given size
  80791. * @param texture Texture to copy from
  80792. * @param width Desired width
  80793. * @param height Desired height
  80794. * @return Generated texture
  80795. */
  80796. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  80797. if (useBilinearMode === void 0) { useBilinearMode = true; }
  80798. var scene = texture.getScene();
  80799. var engine = scene.getEngine();
  80800. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  80801. rtt.wrapU = texture.wrapU;
  80802. rtt.wrapV = texture.wrapV;
  80803. rtt.uOffset = texture.uOffset;
  80804. rtt.vOffset = texture.vOffset;
  80805. rtt.uScale = texture.uScale;
  80806. rtt.vScale = texture.vScale;
  80807. rtt.uAng = texture.uAng;
  80808. rtt.vAng = texture.vAng;
  80809. rtt.wAng = texture.wAng;
  80810. rtt.coordinatesIndex = texture.coordinatesIndex;
  80811. rtt.level = texture.level;
  80812. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  80813. rtt._texture.isReady = false;
  80814. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80815. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80816. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80817. passPostProcess.getEffect().executeWhenCompiled(function () {
  80818. passPostProcess.onApply = function (effect) {
  80819. effect.setTexture("textureSampler", texture);
  80820. };
  80821. var internalTexture = rtt.getInternalTexture();
  80822. if (internalTexture) {
  80823. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  80824. engine.unBindFramebuffer(internalTexture);
  80825. rtt.disposeFramebufferObjects();
  80826. passPostProcess.dispose();
  80827. internalTexture.isReady = true;
  80828. }
  80829. });
  80830. return rtt;
  80831. };
  80832. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  80833. if (!scene._environmentBRDFTexture) {
  80834. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80835. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80836. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80837. scene._environmentBRDFTexture = texture;
  80838. }
  80839. return scene._environmentBRDFTexture;
  80840. };
  80841. 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=";
  80842. return TextureTools;
  80843. }());
  80844. BABYLON.TextureTools = TextureTools;
  80845. })(BABYLON || (BABYLON = {}));
  80846. //# sourceMappingURL=babylon.textureTools.js.map
  80847. var BABYLON;
  80848. (function (BABYLON) {
  80849. var FramingBehavior = /** @class */ (function () {
  80850. function FramingBehavior() {
  80851. this._mode = FramingBehavior.FitFrustumSidesMode;
  80852. this._radiusScale = 1.0;
  80853. this._positionScale = 0.5;
  80854. this._defaultElevation = 0.3;
  80855. this._elevationReturnTime = 1500;
  80856. this._elevationReturnWaitTime = 1000;
  80857. this._zoomStopsAnimation = false;
  80858. this._framingTime = 1500;
  80859. this._isPointerDown = false;
  80860. this._lastInteractionTime = -Infinity;
  80861. // Framing control
  80862. this._animatables = new Array();
  80863. this._betaIsAnimating = false;
  80864. }
  80865. Object.defineProperty(FramingBehavior.prototype, "name", {
  80866. get: function () {
  80867. return "Framing";
  80868. },
  80869. enumerable: true,
  80870. configurable: true
  80871. });
  80872. Object.defineProperty(FramingBehavior.prototype, "mode", {
  80873. /**
  80874. * Gets current mode used by the behavior.
  80875. */
  80876. get: function () {
  80877. return this._mode;
  80878. },
  80879. /**
  80880. * Sets the current mode used by the behavior
  80881. */
  80882. set: function (mode) {
  80883. this._mode = mode;
  80884. },
  80885. enumerable: true,
  80886. configurable: true
  80887. });
  80888. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  80889. /**
  80890. * Gets the scale applied to the radius
  80891. */
  80892. get: function () {
  80893. return this._radiusScale;
  80894. },
  80895. /**
  80896. * Sets the scale applied to the radius (1 by default)
  80897. */
  80898. set: function (radius) {
  80899. this._radiusScale = radius;
  80900. },
  80901. enumerable: true,
  80902. configurable: true
  80903. });
  80904. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  80905. /**
  80906. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80907. */
  80908. get: function () {
  80909. return this._positionScale;
  80910. },
  80911. /**
  80912. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80913. */
  80914. set: function (scale) {
  80915. this._positionScale = scale;
  80916. },
  80917. enumerable: true,
  80918. configurable: true
  80919. });
  80920. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  80921. /**
  80922. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80923. * behaviour is triggered, in radians.
  80924. */
  80925. get: function () {
  80926. return this._defaultElevation;
  80927. },
  80928. /**
  80929. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80930. * behaviour is triggered, in radians.
  80931. */
  80932. set: function (elevation) {
  80933. this._defaultElevation = elevation;
  80934. },
  80935. enumerable: true,
  80936. configurable: true
  80937. });
  80938. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  80939. /**
  80940. * Gets the time (in milliseconds) taken to return to the default beta position.
  80941. * Negative value indicates camera should not return to default.
  80942. */
  80943. get: function () {
  80944. return this._elevationReturnTime;
  80945. },
  80946. /**
  80947. * Sets the time (in milliseconds) taken to return to the default beta position.
  80948. * Negative value indicates camera should not return to default.
  80949. */
  80950. set: function (speed) {
  80951. this._elevationReturnTime = speed;
  80952. },
  80953. enumerable: true,
  80954. configurable: true
  80955. });
  80956. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  80957. /**
  80958. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80959. */
  80960. get: function () {
  80961. return this._elevationReturnWaitTime;
  80962. },
  80963. /**
  80964. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80965. */
  80966. set: function (time) {
  80967. this._elevationReturnWaitTime = time;
  80968. },
  80969. enumerable: true,
  80970. configurable: true
  80971. });
  80972. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  80973. /**
  80974. * Gets the flag that indicates if user zooming should stop animation.
  80975. */
  80976. get: function () {
  80977. return this._zoomStopsAnimation;
  80978. },
  80979. /**
  80980. * Sets the flag that indicates if user zooming should stop animation.
  80981. */
  80982. set: function (flag) {
  80983. this._zoomStopsAnimation = flag;
  80984. },
  80985. enumerable: true,
  80986. configurable: true
  80987. });
  80988. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  80989. /**
  80990. * Gets the transition time when framing the mesh, in milliseconds
  80991. */
  80992. get: function () {
  80993. return this._framingTime;
  80994. },
  80995. /**
  80996. * Sets the transition time when framing the mesh, in milliseconds
  80997. */
  80998. set: function (time) {
  80999. this._framingTime = time;
  81000. },
  81001. enumerable: true,
  81002. configurable: true
  81003. });
  81004. FramingBehavior.prototype.init = function () {
  81005. // Do notihng
  81006. };
  81007. FramingBehavior.prototype.attach = function (camera) {
  81008. var _this = this;
  81009. this._attachedCamera = camera;
  81010. var scene = this._attachedCamera.getScene();
  81011. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  81012. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81013. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81014. _this._isPointerDown = true;
  81015. return;
  81016. }
  81017. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81018. _this._isPointerDown = false;
  81019. }
  81020. });
  81021. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81022. if (mesh) {
  81023. _this.zoomOnMesh(mesh);
  81024. }
  81025. });
  81026. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81027. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81028. _this._applyUserInteraction();
  81029. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  81030. // back to the default position after a given timeout
  81031. _this._maintainCameraAboveGround();
  81032. });
  81033. };
  81034. FramingBehavior.prototype.detach = function () {
  81035. if (!this._attachedCamera) {
  81036. return;
  81037. }
  81038. var scene = this._attachedCamera.getScene();
  81039. if (this._onPrePointerObservableObserver) {
  81040. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81041. }
  81042. if (this._onAfterCheckInputsObserver) {
  81043. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81044. }
  81045. if (this._onMeshTargetChangedObserver) {
  81046. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81047. }
  81048. this._attachedCamera = null;
  81049. };
  81050. /**
  81051. * Targets the given mesh and updates zoom level accordingly.
  81052. * @param mesh The mesh to target.
  81053. * @param radius Optional. If a cached radius position already exists, overrides default.
  81054. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81055. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81056. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81057. */
  81058. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81059. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81060. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81061. mesh.computeWorldMatrix(true);
  81062. var boundingBox = mesh.getBoundingInfo().boundingBox;
  81063. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  81064. };
  81065. /**
  81066. * Targets the given mesh with its children and updates zoom level accordingly.
  81067. * @param mesh The mesh to target.
  81068. * @param radius Optional. If a cached radius position already exists, overrides default.
  81069. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81070. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81071. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81072. */
  81073. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81074. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81075. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81076. mesh.computeWorldMatrix(true);
  81077. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  81078. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  81079. };
  81080. /**
  81081. * Targets the given meshes with their children and updates zoom level accordingly.
  81082. * @param meshes The mesh to target.
  81083. * @param radius Optional. If a cached radius position already exists, overrides default.
  81084. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81085. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81086. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81087. */
  81088. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  81089. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81090. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81091. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81092. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81093. for (var i = 0; i < meshes.length; i++) {
  81094. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  81095. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  81096. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  81097. }
  81098. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  81099. };
  81100. /**
  81101. * Targets the given mesh and updates zoom level accordingly.
  81102. * @param mesh The mesh to target.
  81103. * @param radius Optional. If a cached radius position already exists, overrides default.
  81104. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81105. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81106. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81107. */
  81108. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  81109. var _this = this;
  81110. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81111. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81112. var zoomTarget;
  81113. if (!this._attachedCamera) {
  81114. return;
  81115. }
  81116. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  81117. var bottom = minimumWorld.y;
  81118. var top = maximumWorld.y;
  81119. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  81120. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  81121. if (focusOnOriginXZ) {
  81122. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  81123. }
  81124. else {
  81125. var centerWorld = minimumWorld.add(radiusWorld);
  81126. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  81127. }
  81128. if (!this._vectorTransition) {
  81129. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  81130. }
  81131. this._betaIsAnimating = true;
  81132. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  81133. if (animatable) {
  81134. this._animatables.push(animatable);
  81135. }
  81136. // sets the radius and lower radius bounds
  81137. // Small delta ensures camera is not always at lower zoom limit.
  81138. var radius = 0;
  81139. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  81140. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81141. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  81142. radius = position;
  81143. }
  81144. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81145. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81146. if (this._attachedCamera.lowerRadiusLimit === null) {
  81147. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  81148. }
  81149. }
  81150. // Set sensibilities
  81151. var extend = maximumWorld.subtract(minimumWorld).length();
  81152. this._attachedCamera.panningSensibility = 5000 / extend;
  81153. this._attachedCamera.wheelPrecision = 100 / radius;
  81154. // transition to new radius
  81155. if (!this._radiusTransition) {
  81156. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81157. }
  81158. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  81159. if (onAnimationEnd) {
  81160. onAnimationEnd();
  81161. }
  81162. if (_this._attachedCamera) {
  81163. _this._attachedCamera.storeState();
  81164. }
  81165. });
  81166. if (animatable) {
  81167. this._animatables.push(animatable);
  81168. }
  81169. };
  81170. /**
  81171. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  81172. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  81173. * frustum width.
  81174. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  81175. * to fully enclose the mesh in the viewing frustum.
  81176. */
  81177. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  81178. var size = maximumWorld.subtract(minimumWorld);
  81179. var boxVectorGlobalDiagonal = size.length();
  81180. var frustumSlope = this._getFrustumSlope();
  81181. // Formula for setting distance
  81182. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  81183. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  81184. // Horizon distance
  81185. var radius = radiusWithoutFraming * this._radiusScale;
  81186. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  81187. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  81188. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  81189. var camera = this._attachedCamera;
  81190. if (!camera) {
  81191. return 0;
  81192. }
  81193. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81194. // Don't exceed the requested limit
  81195. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  81196. }
  81197. // Don't exceed the upper radius limit
  81198. if (camera.upperRadiusLimit) {
  81199. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  81200. }
  81201. return distance;
  81202. };
  81203. /**
  81204. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  81205. * is automatically returned to its default position (expected to be above ground plane).
  81206. */
  81207. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  81208. var _this = this;
  81209. if (this._elevationReturnTime < 0) {
  81210. return;
  81211. }
  81212. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  81213. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  81214. var limitBeta = Math.PI * 0.5;
  81215. // Bring the camera back up if below the ground plane
  81216. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  81217. this._betaIsAnimating = true;
  81218. //Transition to new position
  81219. this.stopAllAnimations();
  81220. if (!this._betaTransition) {
  81221. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81222. }
  81223. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  81224. _this._clearAnimationLocks();
  81225. _this.stopAllAnimations();
  81226. });
  81227. if (animatabe) {
  81228. this._animatables.push(animatabe);
  81229. }
  81230. }
  81231. };
  81232. /**
  81233. * Returns the frustum slope based on the canvas ratio and camera FOV
  81234. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  81235. */
  81236. FramingBehavior.prototype._getFrustumSlope = function () {
  81237. // Calculate the viewport ratio
  81238. // Aspect Ratio is Height/Width.
  81239. var camera = this._attachedCamera;
  81240. if (!camera) {
  81241. return BABYLON.Vector2.Zero();
  81242. }
  81243. var engine = camera.getScene().getEngine();
  81244. var aspectRatio = engine.getAspectRatio(camera);
  81245. // Camera FOV is the vertical field of view (top-bottom) in radians.
  81246. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  81247. var frustumSlopeY = Math.tan(camera.fov / 2);
  81248. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  81249. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  81250. // along the forward vector.
  81251. var frustumSlopeX = frustumSlopeY * aspectRatio;
  81252. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  81253. };
  81254. /**
  81255. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  81256. */
  81257. FramingBehavior.prototype._clearAnimationLocks = function () {
  81258. this._betaIsAnimating = false;
  81259. };
  81260. /**
  81261. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81262. */
  81263. FramingBehavior.prototype._applyUserInteraction = function () {
  81264. if (this.isUserIsMoving) {
  81265. this._lastInteractionTime = BABYLON.Tools.Now;
  81266. this.stopAllAnimations();
  81267. this._clearAnimationLocks();
  81268. }
  81269. };
  81270. /**
  81271. * Stops and removes all animations that have been applied to the camera
  81272. */
  81273. FramingBehavior.prototype.stopAllAnimations = function () {
  81274. if (this._attachedCamera) {
  81275. this._attachedCamera.animations = [];
  81276. }
  81277. while (this._animatables.length) {
  81278. if (this._animatables[0]) {
  81279. this._animatables[0].onAnimationEnd = null;
  81280. this._animatables[0].stop();
  81281. }
  81282. this._animatables.shift();
  81283. }
  81284. };
  81285. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  81286. /**
  81287. * Gets a value indicating if the user is moving the camera
  81288. */
  81289. get: function () {
  81290. if (!this._attachedCamera) {
  81291. return false;
  81292. }
  81293. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81294. this._attachedCamera.inertialBetaOffset !== 0 ||
  81295. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81296. this._attachedCamera.inertialPanningX !== 0 ||
  81297. this._attachedCamera.inertialPanningY !== 0 ||
  81298. this._isPointerDown;
  81299. },
  81300. enumerable: true,
  81301. configurable: true
  81302. });
  81303. /**
  81304. * The easing function used by animations
  81305. */
  81306. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  81307. /**
  81308. * The easing mode used by animations
  81309. */
  81310. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  81311. // Statics
  81312. /**
  81313. * The camera can move all the way towards the mesh.
  81314. */
  81315. FramingBehavior.IgnoreBoundsSizeMode = 0;
  81316. /**
  81317. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  81318. */
  81319. FramingBehavior.FitFrustumSidesMode = 1;
  81320. return FramingBehavior;
  81321. }());
  81322. BABYLON.FramingBehavior = FramingBehavior;
  81323. })(BABYLON || (BABYLON = {}));
  81324. //# sourceMappingURL=babylon.framingBehavior.js.map
  81325. var BABYLON;
  81326. (function (BABYLON) {
  81327. /**
  81328. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  81329. */
  81330. var BouncingBehavior = /** @class */ (function () {
  81331. function BouncingBehavior() {
  81332. /**
  81333. * The duration of the animation, in milliseconds
  81334. */
  81335. this.transitionDuration = 450;
  81336. /**
  81337. * Length of the distance animated by the transition when lower radius is reached
  81338. */
  81339. this.lowerRadiusTransitionRange = 2;
  81340. /**
  81341. * Length of the distance animated by the transition when upper radius is reached
  81342. */
  81343. this.upperRadiusTransitionRange = -2;
  81344. this._autoTransitionRange = false;
  81345. // Animations
  81346. this._radiusIsAnimating = false;
  81347. this._radiusBounceTransition = null;
  81348. this._animatables = new Array();
  81349. }
  81350. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81351. get: function () {
  81352. return "Bouncing";
  81353. },
  81354. enumerable: true,
  81355. configurable: true
  81356. });
  81357. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81358. /**
  81359. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81360. */
  81361. get: function () {
  81362. return this._autoTransitionRange;
  81363. },
  81364. /**
  81365. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81366. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81367. */
  81368. set: function (value) {
  81369. var _this = this;
  81370. if (this._autoTransitionRange === value) {
  81371. return;
  81372. }
  81373. this._autoTransitionRange = value;
  81374. var camera = this._attachedCamera;
  81375. if (!camera) {
  81376. return;
  81377. }
  81378. if (value) {
  81379. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81380. if (!mesh) {
  81381. return;
  81382. }
  81383. mesh.computeWorldMatrix(true);
  81384. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81385. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81386. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81387. });
  81388. }
  81389. else if (this._onMeshTargetChangedObserver) {
  81390. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81391. }
  81392. },
  81393. enumerable: true,
  81394. configurable: true
  81395. });
  81396. BouncingBehavior.prototype.init = function () {
  81397. // Do notihng
  81398. };
  81399. BouncingBehavior.prototype.attach = function (camera) {
  81400. var _this = this;
  81401. this._attachedCamera = camera;
  81402. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81403. if (!_this._attachedCamera) {
  81404. return;
  81405. }
  81406. // Add the bounce animation to the lower radius limit
  81407. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  81408. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  81409. }
  81410. // Add the bounce animation to the upper radius limit
  81411. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  81412. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  81413. }
  81414. });
  81415. };
  81416. BouncingBehavior.prototype.detach = function () {
  81417. if (!this._attachedCamera) {
  81418. return;
  81419. }
  81420. if (this._onAfterCheckInputsObserver) {
  81421. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81422. }
  81423. if (this._onMeshTargetChangedObserver) {
  81424. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81425. }
  81426. this._attachedCamera = null;
  81427. };
  81428. /**
  81429. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  81430. * @param radiusLimit The limit to check against.
  81431. * @return Bool to indicate if at limit.
  81432. */
  81433. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  81434. if (!this._attachedCamera) {
  81435. return false;
  81436. }
  81437. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  81438. return true;
  81439. }
  81440. return false;
  81441. };
  81442. /**
  81443. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  81444. * @param radiusDelta The delta by which to animate to. Can be negative.
  81445. */
  81446. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  81447. var _this = this;
  81448. if (!this._attachedCamera) {
  81449. return;
  81450. }
  81451. if (!this._radiusBounceTransition) {
  81452. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  81453. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  81454. }
  81455. // Prevent zoom until bounce has completed
  81456. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  81457. this._attachedCamera.wheelPrecision = Infinity;
  81458. this._attachedCamera.inertialRadiusOffset = 0;
  81459. // Animate to the radius limit
  81460. this.stopAllAnimations();
  81461. this._radiusIsAnimating = true;
  81462. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  81463. if (animatable) {
  81464. this._animatables.push(animatable);
  81465. }
  81466. };
  81467. /**
  81468. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  81469. */
  81470. BouncingBehavior.prototype._clearAnimationLocks = function () {
  81471. this._radiusIsAnimating = false;
  81472. if (this._attachedCamera) {
  81473. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  81474. }
  81475. };
  81476. /**
  81477. * Stops and removes all animations that have been applied to the camera
  81478. */
  81479. BouncingBehavior.prototype.stopAllAnimations = function () {
  81480. if (this._attachedCamera) {
  81481. this._attachedCamera.animations = [];
  81482. }
  81483. while (this._animatables.length) {
  81484. this._animatables[0].onAnimationEnd = null;
  81485. this._animatables[0].stop();
  81486. this._animatables.shift();
  81487. }
  81488. };
  81489. /**
  81490. * The easing function used by animations
  81491. */
  81492. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  81493. /**
  81494. * The easing mode used by animations
  81495. */
  81496. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  81497. return BouncingBehavior;
  81498. }());
  81499. BABYLON.BouncingBehavior = BouncingBehavior;
  81500. })(BABYLON || (BABYLON = {}));
  81501. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  81502. var BABYLON;
  81503. (function (BABYLON) {
  81504. var AutoRotationBehavior = /** @class */ (function () {
  81505. function AutoRotationBehavior() {
  81506. this._zoomStopsAnimation = false;
  81507. this._idleRotationSpeed = 0.05;
  81508. this._idleRotationWaitTime = 2000;
  81509. this._idleRotationSpinupTime = 2000;
  81510. this._isPointerDown = false;
  81511. this._lastFrameTime = null;
  81512. this._lastInteractionTime = -Infinity;
  81513. this._cameraRotationSpeed = 0;
  81514. this._lastFrameRadius = 0;
  81515. }
  81516. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  81517. get: function () {
  81518. return "AutoRotation";
  81519. },
  81520. enumerable: true,
  81521. configurable: true
  81522. });
  81523. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  81524. /**
  81525. * Gets the flag that indicates if user zooming should stop animation.
  81526. */
  81527. get: function () {
  81528. return this._zoomStopsAnimation;
  81529. },
  81530. /**
  81531. * Sets the flag that indicates if user zooming should stop animation.
  81532. */
  81533. set: function (flag) {
  81534. this._zoomStopsAnimation = flag;
  81535. },
  81536. enumerable: true,
  81537. configurable: true
  81538. });
  81539. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  81540. /**
  81541. * Gets the default speed at which the camera rotates around the model.
  81542. */
  81543. get: function () {
  81544. return this._idleRotationSpeed;
  81545. },
  81546. /**
  81547. * Sets the default speed at which the camera rotates around the model.
  81548. */
  81549. set: function (speed) {
  81550. this._idleRotationSpeed = speed;
  81551. },
  81552. enumerable: true,
  81553. configurable: true
  81554. });
  81555. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  81556. /**
  81557. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  81558. */
  81559. get: function () {
  81560. return this._idleRotationWaitTime;
  81561. },
  81562. /**
  81563. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  81564. */
  81565. set: function (time) {
  81566. this._idleRotationWaitTime = time;
  81567. },
  81568. enumerable: true,
  81569. configurable: true
  81570. });
  81571. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  81572. /**
  81573. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81574. */
  81575. get: function () {
  81576. return this._idleRotationSpinupTime;
  81577. },
  81578. /**
  81579. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81580. */
  81581. set: function (time) {
  81582. this._idleRotationSpinupTime = time;
  81583. },
  81584. enumerable: true,
  81585. configurable: true
  81586. });
  81587. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  81588. /**
  81589. * Gets a value indicating if the camera is currently rotating because of this behavior
  81590. */
  81591. get: function () {
  81592. return Math.abs(this._cameraRotationSpeed) > 0;
  81593. },
  81594. enumerable: true,
  81595. configurable: true
  81596. });
  81597. AutoRotationBehavior.prototype.init = function () {
  81598. // Do notihng
  81599. };
  81600. AutoRotationBehavior.prototype.attach = function (camera) {
  81601. var _this = this;
  81602. this._attachedCamera = camera;
  81603. var scene = this._attachedCamera.getScene();
  81604. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81605. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81606. _this._isPointerDown = true;
  81607. return;
  81608. }
  81609. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81610. _this._isPointerDown = false;
  81611. }
  81612. });
  81613. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81614. var now = BABYLON.Tools.Now;
  81615. var dt = 0;
  81616. if (_this._lastFrameTime != null) {
  81617. dt = now - _this._lastFrameTime;
  81618. }
  81619. _this._lastFrameTime = now;
  81620. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81621. _this._applyUserInteraction();
  81622. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  81623. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  81624. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  81625. // Step camera rotation by rotation speed
  81626. if (_this._attachedCamera) {
  81627. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  81628. }
  81629. });
  81630. };
  81631. AutoRotationBehavior.prototype.detach = function () {
  81632. if (!this._attachedCamera) {
  81633. return;
  81634. }
  81635. var scene = this._attachedCamera.getScene();
  81636. if (this._onPrePointerObservableObserver) {
  81637. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81638. }
  81639. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81640. this._attachedCamera = null;
  81641. };
  81642. /**
  81643. * Returns true if user is scrolling.
  81644. * @return true if user is scrolling.
  81645. */
  81646. AutoRotationBehavior.prototype._userIsZooming = function () {
  81647. if (!this._attachedCamera) {
  81648. return false;
  81649. }
  81650. return this._attachedCamera.inertialRadiusOffset !== 0;
  81651. };
  81652. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  81653. if (!this._attachedCamera) {
  81654. return false;
  81655. }
  81656. var zoomHasHitLimit = false;
  81657. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  81658. zoomHasHitLimit = true;
  81659. }
  81660. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  81661. this._lastFrameRadius = this._attachedCamera.radius;
  81662. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  81663. };
  81664. /**
  81665. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81666. */
  81667. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  81668. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  81669. this._lastInteractionTime = BABYLON.Tools.Now;
  81670. }
  81671. };
  81672. // Tools
  81673. AutoRotationBehavior.prototype._userIsMoving = function () {
  81674. if (!this._attachedCamera) {
  81675. return false;
  81676. }
  81677. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81678. this._attachedCamera.inertialBetaOffset !== 0 ||
  81679. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81680. this._attachedCamera.inertialPanningX !== 0 ||
  81681. this._attachedCamera.inertialPanningY !== 0 ||
  81682. this._isPointerDown;
  81683. };
  81684. return AutoRotationBehavior;
  81685. }());
  81686. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  81687. })(BABYLON || (BABYLON = {}));
  81688. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  81689. var BABYLON;
  81690. (function (BABYLON) {
  81691. /**
  81692. * This class can be used to get instrumentation data from a Babylon engine
  81693. */
  81694. var EngineInstrumentation = /** @class */ (function () {
  81695. function EngineInstrumentation(engine) {
  81696. this.engine = engine;
  81697. this._captureGPUFrameTime = false;
  81698. this._gpuFrameTime = new BABYLON.PerfCounter();
  81699. this._captureShaderCompilationTime = false;
  81700. this._shaderCompilationTime = new BABYLON.PerfCounter();
  81701. // Observers
  81702. this._onBeginFrameObserver = null;
  81703. this._onEndFrameObserver = null;
  81704. this._onBeforeShaderCompilationObserver = null;
  81705. this._onAfterShaderCompilationObserver = null;
  81706. }
  81707. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  81708. // Properties
  81709. /**
  81710. * Gets the perf counter used for GPU frame time
  81711. */
  81712. get: function () {
  81713. return this._gpuFrameTime;
  81714. },
  81715. enumerable: true,
  81716. configurable: true
  81717. });
  81718. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  81719. /**
  81720. * Gets the GPU frame time capture status
  81721. */
  81722. get: function () {
  81723. return this._captureGPUFrameTime;
  81724. },
  81725. /**
  81726. * Enable or disable the GPU frame time capture
  81727. */
  81728. set: function (value) {
  81729. var _this = this;
  81730. if (value === this._captureGPUFrameTime) {
  81731. return;
  81732. }
  81733. this._captureGPUFrameTime = value;
  81734. if (value) {
  81735. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  81736. if (!_this._gpuFrameTimeToken) {
  81737. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  81738. }
  81739. });
  81740. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  81741. if (!_this._gpuFrameTimeToken) {
  81742. return;
  81743. }
  81744. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  81745. if (time > -1) {
  81746. _this._gpuFrameTimeToken = null;
  81747. _this._gpuFrameTime.fetchNewFrame();
  81748. _this._gpuFrameTime.addCount(time, true);
  81749. }
  81750. });
  81751. }
  81752. else {
  81753. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81754. this._onBeginFrameObserver = null;
  81755. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81756. this._onEndFrameObserver = null;
  81757. }
  81758. },
  81759. enumerable: true,
  81760. configurable: true
  81761. });
  81762. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  81763. /**
  81764. * Gets the perf counter used for shader compilation time
  81765. */
  81766. get: function () {
  81767. return this._shaderCompilationTime;
  81768. },
  81769. enumerable: true,
  81770. configurable: true
  81771. });
  81772. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  81773. /**
  81774. * Gets the shader compilation time capture status
  81775. */
  81776. get: function () {
  81777. return this._captureShaderCompilationTime;
  81778. },
  81779. /**
  81780. * Enable or disable the shader compilation time capture
  81781. */
  81782. set: function (value) {
  81783. var _this = this;
  81784. if (value === this._captureShaderCompilationTime) {
  81785. return;
  81786. }
  81787. this._captureShaderCompilationTime = value;
  81788. if (value) {
  81789. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  81790. _this._shaderCompilationTime.fetchNewFrame();
  81791. _this._shaderCompilationTime.beginMonitoring();
  81792. });
  81793. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  81794. _this._shaderCompilationTime.endMonitoring();
  81795. });
  81796. }
  81797. else {
  81798. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81799. this._onBeforeShaderCompilationObserver = null;
  81800. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81801. this._onAfterShaderCompilationObserver = null;
  81802. }
  81803. },
  81804. enumerable: true,
  81805. configurable: true
  81806. });
  81807. EngineInstrumentation.prototype.dispose = function () {
  81808. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81809. this._onBeginFrameObserver = null;
  81810. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81811. this._onEndFrameObserver = null;
  81812. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81813. this._onBeforeShaderCompilationObserver = null;
  81814. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81815. this._onAfterShaderCompilationObserver = null;
  81816. this.engine = null;
  81817. };
  81818. return EngineInstrumentation;
  81819. }());
  81820. BABYLON.EngineInstrumentation = EngineInstrumentation;
  81821. })(BABYLON || (BABYLON = {}));
  81822. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  81823. var BABYLON;
  81824. (function (BABYLON) {
  81825. /**
  81826. * This class can be used to get instrumentation data from a Babylon engine
  81827. */
  81828. var SceneInstrumentation = /** @class */ (function () {
  81829. function SceneInstrumentation(scene) {
  81830. var _this = this;
  81831. this.scene = scene;
  81832. this._captureActiveMeshesEvaluationTime = false;
  81833. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  81834. this._captureRenderTargetsRenderTime = false;
  81835. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  81836. this._captureFrameTime = false;
  81837. this._frameTime = new BABYLON.PerfCounter();
  81838. this._captureRenderTime = false;
  81839. this._renderTime = new BABYLON.PerfCounter();
  81840. this._captureInterFrameTime = false;
  81841. this._interFrameTime = new BABYLON.PerfCounter();
  81842. this._captureParticlesRenderTime = false;
  81843. this._particlesRenderTime = new BABYLON.PerfCounter();
  81844. this._captureSpritesRenderTime = false;
  81845. this._spritesRenderTime = new BABYLON.PerfCounter();
  81846. this._capturePhysicsTime = false;
  81847. this._physicsTime = new BABYLON.PerfCounter();
  81848. this._captureAnimationsTime = false;
  81849. this._animationsTime = new BABYLON.PerfCounter();
  81850. // Observers
  81851. this._onBeforeActiveMeshesEvaluationObserver = null;
  81852. this._onAfterActiveMeshesEvaluationObserver = null;
  81853. this._onBeforeRenderTargetsRenderObserver = null;
  81854. this._onAfterRenderTargetsRenderObserver = null;
  81855. this._onAfterRenderObserver = null;
  81856. this._onBeforeDrawPhaseObserver = null;
  81857. this._onAfterDrawPhaseObserver = null;
  81858. this._onBeforeAnimationsObserver = null;
  81859. this._onBeforeParticlesRenderingObserver = null;
  81860. this._onAfterParticlesRenderingObserver = null;
  81861. this._onBeforeSpritesRenderingObserver = null;
  81862. this._onAfterSpritesRenderingObserver = null;
  81863. this._onBeforePhysicsObserver = null;
  81864. this._onAfterPhysicsObserver = null;
  81865. this._onAfterAnimationsObserver = null;
  81866. // Before render
  81867. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  81868. if (_this._captureActiveMeshesEvaluationTime) {
  81869. _this._activeMeshesEvaluationTime.fetchNewFrame();
  81870. }
  81871. if (_this._captureRenderTargetsRenderTime) {
  81872. _this._renderTargetsRenderTime.fetchNewFrame();
  81873. }
  81874. if (_this._captureFrameTime) {
  81875. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  81876. _this._frameTime.beginMonitoring();
  81877. }
  81878. if (_this._captureInterFrameTime) {
  81879. _this._interFrameTime.endMonitoring();
  81880. }
  81881. if (_this._captureParticlesRenderTime) {
  81882. _this._particlesRenderTime.fetchNewFrame();
  81883. }
  81884. if (_this._captureSpritesRenderTime) {
  81885. _this._spritesRenderTime.fetchNewFrame();
  81886. }
  81887. if (_this._captureAnimationsTime) {
  81888. _this._animationsTime.beginMonitoring();
  81889. }
  81890. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  81891. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  81892. });
  81893. // After render
  81894. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  81895. if (_this._captureFrameTime) {
  81896. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  81897. _this._frameTime.endMonitoring();
  81898. }
  81899. if (_this._captureRenderTime) {
  81900. _this._renderTime.endMonitoring(false);
  81901. }
  81902. if (_this._captureInterFrameTime) {
  81903. _this._interFrameTime.beginMonitoring();
  81904. }
  81905. });
  81906. }
  81907. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  81908. // Properties
  81909. /**
  81910. * Gets the perf counter used for active meshes evaluation time
  81911. */
  81912. get: function () {
  81913. return this._activeMeshesEvaluationTime;
  81914. },
  81915. enumerable: true,
  81916. configurable: true
  81917. });
  81918. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  81919. /**
  81920. * Gets the active meshes evaluation time capture status
  81921. */
  81922. get: function () {
  81923. return this._captureActiveMeshesEvaluationTime;
  81924. },
  81925. /**
  81926. * Enable or disable the active meshes evaluation time capture
  81927. */
  81928. set: function (value) {
  81929. var _this = this;
  81930. if (value === this._captureActiveMeshesEvaluationTime) {
  81931. return;
  81932. }
  81933. this._captureActiveMeshesEvaluationTime = value;
  81934. if (value) {
  81935. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  81936. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  81937. _this._activeMeshesEvaluationTime.beginMonitoring();
  81938. });
  81939. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  81940. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  81941. _this._activeMeshesEvaluationTime.endMonitoring();
  81942. });
  81943. }
  81944. else {
  81945. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  81946. this._onBeforeActiveMeshesEvaluationObserver = null;
  81947. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  81948. this._onAfterActiveMeshesEvaluationObserver = null;
  81949. }
  81950. },
  81951. enumerable: true,
  81952. configurable: true
  81953. });
  81954. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  81955. /**
  81956. * Gets the perf counter used for render targets render time
  81957. */
  81958. get: function () {
  81959. return this._renderTargetsRenderTime;
  81960. },
  81961. enumerable: true,
  81962. configurable: true
  81963. });
  81964. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  81965. /**
  81966. * Gets the render targets render time capture status
  81967. */
  81968. get: function () {
  81969. return this._captureRenderTargetsRenderTime;
  81970. },
  81971. /**
  81972. * Enable or disable the render targets render time capture
  81973. */
  81974. set: function (value) {
  81975. var _this = this;
  81976. if (value === this._captureRenderTargetsRenderTime) {
  81977. return;
  81978. }
  81979. this._captureRenderTargetsRenderTime = value;
  81980. if (value) {
  81981. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  81982. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  81983. _this._renderTargetsRenderTime.beginMonitoring();
  81984. });
  81985. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  81986. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  81987. _this._renderTargetsRenderTime.endMonitoring(false);
  81988. });
  81989. }
  81990. else {
  81991. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  81992. this._onBeforeRenderTargetsRenderObserver = null;
  81993. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  81994. this._onAfterRenderTargetsRenderObserver = null;
  81995. }
  81996. },
  81997. enumerable: true,
  81998. configurable: true
  81999. });
  82000. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  82001. /**
  82002. * Gets the perf counter used for particles render time
  82003. */
  82004. get: function () {
  82005. return this._particlesRenderTime;
  82006. },
  82007. enumerable: true,
  82008. configurable: true
  82009. });
  82010. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  82011. /**
  82012. * Gets the particles render time capture status
  82013. */
  82014. get: function () {
  82015. return this._captureParticlesRenderTime;
  82016. },
  82017. /**
  82018. * Enable or disable the particles render time capture
  82019. */
  82020. set: function (value) {
  82021. var _this = this;
  82022. if (value === this._captureParticlesRenderTime) {
  82023. return;
  82024. }
  82025. this._captureParticlesRenderTime = value;
  82026. if (value) {
  82027. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  82028. BABYLON.Tools.StartPerformanceCounter("Particles");
  82029. _this._particlesRenderTime.beginMonitoring();
  82030. });
  82031. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  82032. BABYLON.Tools.EndPerformanceCounter("Particles");
  82033. _this._particlesRenderTime.endMonitoring(false);
  82034. });
  82035. }
  82036. else {
  82037. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82038. this._onBeforeParticlesRenderingObserver = null;
  82039. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82040. this._onAfterParticlesRenderingObserver = null;
  82041. }
  82042. },
  82043. enumerable: true,
  82044. configurable: true
  82045. });
  82046. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  82047. /**
  82048. * Gets the perf counter used for sprites render time
  82049. */
  82050. get: function () {
  82051. return this._spritesRenderTime;
  82052. },
  82053. enumerable: true,
  82054. configurable: true
  82055. });
  82056. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  82057. /**
  82058. * Gets the sprites render time capture status
  82059. */
  82060. get: function () {
  82061. return this._captureSpritesRenderTime;
  82062. },
  82063. /**
  82064. * Enable or disable the sprites render time capture
  82065. */
  82066. set: function (value) {
  82067. var _this = this;
  82068. if (value === this._captureSpritesRenderTime) {
  82069. return;
  82070. }
  82071. this._captureSpritesRenderTime = value;
  82072. if (value) {
  82073. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  82074. BABYLON.Tools.StartPerformanceCounter("Sprites");
  82075. _this._spritesRenderTime.beginMonitoring();
  82076. });
  82077. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  82078. BABYLON.Tools.EndPerformanceCounter("Sprites");
  82079. _this._spritesRenderTime.endMonitoring(false);
  82080. });
  82081. }
  82082. else {
  82083. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82084. this._onBeforeSpritesRenderingObserver = null;
  82085. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82086. this._onAfterSpritesRenderingObserver = null;
  82087. }
  82088. },
  82089. enumerable: true,
  82090. configurable: true
  82091. });
  82092. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  82093. /**
  82094. * Gets the perf counter used for physics time
  82095. */
  82096. get: function () {
  82097. return this._physicsTime;
  82098. },
  82099. enumerable: true,
  82100. configurable: true
  82101. });
  82102. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  82103. /**
  82104. * Gets the physics time capture status
  82105. */
  82106. get: function () {
  82107. return this._capturePhysicsTime;
  82108. },
  82109. /**
  82110. * Enable or disable the physics time capture
  82111. */
  82112. set: function (value) {
  82113. var _this = this;
  82114. if (value === this._capturePhysicsTime) {
  82115. return;
  82116. }
  82117. this._capturePhysicsTime = value;
  82118. if (value) {
  82119. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  82120. BABYLON.Tools.StartPerformanceCounter("Physics");
  82121. _this._physicsTime.beginMonitoring();
  82122. });
  82123. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  82124. BABYLON.Tools.EndPerformanceCounter("Physics");
  82125. _this._physicsTime.endMonitoring();
  82126. });
  82127. }
  82128. else {
  82129. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82130. this._onBeforePhysicsObserver = null;
  82131. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82132. this._onAfterPhysicsObserver = null;
  82133. }
  82134. },
  82135. enumerable: true,
  82136. configurable: true
  82137. });
  82138. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  82139. /**
  82140. * Gets the perf counter used for animations time
  82141. */
  82142. get: function () {
  82143. return this._animationsTime;
  82144. },
  82145. enumerable: true,
  82146. configurable: true
  82147. });
  82148. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  82149. /**
  82150. * Gets the animations time capture status
  82151. */
  82152. get: function () {
  82153. return this._captureAnimationsTime;
  82154. },
  82155. /**
  82156. * Enable or disable the animations time capture
  82157. */
  82158. set: function (value) {
  82159. var _this = this;
  82160. if (value === this._captureAnimationsTime) {
  82161. return;
  82162. }
  82163. this._captureAnimationsTime = value;
  82164. if (value) {
  82165. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  82166. _this._animationsTime.endMonitoring();
  82167. });
  82168. }
  82169. else {
  82170. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82171. this._onAfterAnimationsObserver = null;
  82172. }
  82173. },
  82174. enumerable: true,
  82175. configurable: true
  82176. });
  82177. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  82178. /**
  82179. * Gets the perf counter used for frame time capture
  82180. */
  82181. get: function () {
  82182. return this._frameTime;
  82183. },
  82184. enumerable: true,
  82185. configurable: true
  82186. });
  82187. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  82188. /**
  82189. * Gets the frame time capture status
  82190. */
  82191. get: function () {
  82192. return this._captureFrameTime;
  82193. },
  82194. /**
  82195. * Enable or disable the frame time capture
  82196. */
  82197. set: function (value) {
  82198. this._captureFrameTime = value;
  82199. },
  82200. enumerable: true,
  82201. configurable: true
  82202. });
  82203. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  82204. /**
  82205. * Gets the perf counter used for inter-frames time capture
  82206. */
  82207. get: function () {
  82208. return this._interFrameTime;
  82209. },
  82210. enumerable: true,
  82211. configurable: true
  82212. });
  82213. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  82214. /**
  82215. * Gets the inter-frames time capture status
  82216. */
  82217. get: function () {
  82218. return this._captureInterFrameTime;
  82219. },
  82220. /**
  82221. * Enable or disable the inter-frames time capture
  82222. */
  82223. set: function (value) {
  82224. this._captureInterFrameTime = value;
  82225. },
  82226. enumerable: true,
  82227. configurable: true
  82228. });
  82229. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  82230. /**
  82231. * Gets the perf counter used for render time capture
  82232. */
  82233. get: function () {
  82234. return this._renderTime;
  82235. },
  82236. enumerable: true,
  82237. configurable: true
  82238. });
  82239. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  82240. /**
  82241. * Gets the render time capture status
  82242. */
  82243. get: function () {
  82244. return this._captureRenderTime;
  82245. },
  82246. /**
  82247. * Enable or disable the render time capture
  82248. */
  82249. set: function (value) {
  82250. var _this = this;
  82251. if (value === this._captureRenderTime) {
  82252. return;
  82253. }
  82254. this._captureRenderTime = value;
  82255. if (value) {
  82256. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  82257. _this._renderTime.beginMonitoring();
  82258. BABYLON.Tools.StartPerformanceCounter("Main render");
  82259. });
  82260. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  82261. _this._renderTime.endMonitoring(false);
  82262. BABYLON.Tools.EndPerformanceCounter("Main render");
  82263. });
  82264. }
  82265. else {
  82266. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82267. this._onBeforeDrawPhaseObserver = null;
  82268. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82269. this._onAfterDrawPhaseObserver = null;
  82270. }
  82271. },
  82272. enumerable: true,
  82273. configurable: true
  82274. });
  82275. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  82276. /**
  82277. * Gets the perf counter used for draw calls
  82278. */
  82279. get: function () {
  82280. return this.scene.getEngine()._drawCalls;
  82281. },
  82282. enumerable: true,
  82283. configurable: true
  82284. });
  82285. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  82286. /**
  82287. * Gets the perf counter used for texture collisions
  82288. */
  82289. get: function () {
  82290. return this.scene.getEngine()._textureCollisions;
  82291. },
  82292. enumerable: true,
  82293. configurable: true
  82294. });
  82295. SceneInstrumentation.prototype.dispose = function () {
  82296. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82297. this._onAfterRenderObserver = null;
  82298. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82299. this._onBeforeActiveMeshesEvaluationObserver = null;
  82300. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82301. this._onAfterActiveMeshesEvaluationObserver = null;
  82302. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82303. this._onBeforeRenderTargetsRenderObserver = null;
  82304. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82305. this._onAfterRenderTargetsRenderObserver = null;
  82306. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  82307. this._onBeforeAnimationsObserver = null;
  82308. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82309. this._onBeforeParticlesRenderingObserver = null;
  82310. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82311. this._onAfterParticlesRenderingObserver = null;
  82312. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82313. this._onBeforeSpritesRenderingObserver = null;
  82314. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82315. this._onAfterSpritesRenderingObserver = null;
  82316. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82317. this._onBeforeDrawPhaseObserver = null;
  82318. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82319. this._onAfterDrawPhaseObserver = null;
  82320. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82321. this._onBeforePhysicsObserver = null;
  82322. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82323. this._onAfterPhysicsObserver = null;
  82324. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82325. this._onAfterAnimationsObserver = null;
  82326. this.scene = null;
  82327. };
  82328. return SceneInstrumentation;
  82329. }());
  82330. BABYLON.SceneInstrumentation = SceneInstrumentation;
  82331. })(BABYLON || (BABYLON = {}));
  82332. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  82333. var BABYLON;
  82334. (function (BABYLON) {
  82335. var _TimeToken = /** @class */ (function () {
  82336. function _TimeToken() {
  82337. this._timeElapsedQueryEnded = false;
  82338. }
  82339. return _TimeToken;
  82340. }());
  82341. BABYLON._TimeToken = _TimeToken;
  82342. })(BABYLON || (BABYLON = {}));
  82343. //# sourceMappingURL=babylon.timeToken.js.map
  82344. var BABYLON;
  82345. (function (BABYLON) {
  82346. /**
  82347. * Background material defines definition.
  82348. */
  82349. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  82350. __extends(BackgroundMaterialDefines, _super);
  82351. /**
  82352. * Constructor of the defines.
  82353. */
  82354. function BackgroundMaterialDefines() {
  82355. var _this = _super.call(this) || this;
  82356. /**
  82357. * True if the diffuse texture is in use.
  82358. */
  82359. _this.DIFFUSE = false;
  82360. /**
  82361. * The direct UV channel to use.
  82362. */
  82363. _this.DIFFUSEDIRECTUV = 0;
  82364. /**
  82365. * True if the diffuse texture is in gamma space.
  82366. */
  82367. _this.GAMMADIFFUSE = false;
  82368. /**
  82369. * True if the diffuse texture has opacity in the alpha channel.
  82370. */
  82371. _this.DIFFUSEHASALPHA = false;
  82372. /**
  82373. * True if you want the material to fade to transparent at grazing angle.
  82374. */
  82375. _this.OPACITYFRESNEL = false;
  82376. /**
  82377. * True if an extra blur needs to be added in the reflection.
  82378. */
  82379. _this.REFLECTIONBLUR = false;
  82380. /**
  82381. * True if you want the material to fade to reflection at grazing angle.
  82382. */
  82383. _this.REFLECTIONFRESNEL = false;
  82384. /**
  82385. * True if you want the material to falloff as far as you move away from the scene center.
  82386. */
  82387. _this.REFLECTIONFALLOFF = false;
  82388. /**
  82389. * False if the current Webgl implementation does not support the texture lod extension.
  82390. */
  82391. _this.TEXTURELODSUPPORT = false;
  82392. /**
  82393. * True to ensure the data are premultiplied.
  82394. */
  82395. _this.PREMULTIPLYALPHA = false;
  82396. /**
  82397. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  82398. */
  82399. _this.USERGBCOLOR = false;
  82400. /**
  82401. * True to add noise in order to reduce the banding effect.
  82402. */
  82403. _this.NOISE = false;
  82404. // Image Processing Configuration.
  82405. _this.IMAGEPROCESSING = false;
  82406. _this.VIGNETTE = false;
  82407. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  82408. _this.VIGNETTEBLENDMODEOPAQUE = false;
  82409. _this.TONEMAPPING = false;
  82410. _this.CONTRAST = false;
  82411. _this.COLORCURVES = false;
  82412. _this.COLORGRADING = false;
  82413. _this.COLORGRADING3D = false;
  82414. _this.SAMPLER3DGREENDEPTH = false;
  82415. _this.SAMPLER3DBGRMAP = false;
  82416. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  82417. _this.EXPOSURE = false;
  82418. // Reflection.
  82419. _this.REFLECTION = false;
  82420. _this.REFLECTIONMAP_3D = false;
  82421. _this.REFLECTIONMAP_SPHERICAL = false;
  82422. _this.REFLECTIONMAP_PLANAR = false;
  82423. _this.REFLECTIONMAP_CUBIC = false;
  82424. _this.REFLECTIONMAP_PROJECTION = false;
  82425. _this.REFLECTIONMAP_SKYBOX = false;
  82426. _this.REFLECTIONMAP_EXPLICIT = false;
  82427. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82428. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82429. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82430. _this.INVERTCUBICMAP = false;
  82431. _this.REFLECTIONMAP_OPPOSITEZ = false;
  82432. _this.LODINREFLECTIONALPHA = false;
  82433. _this.GAMMAREFLECTION = false;
  82434. // Default BJS.
  82435. _this.MAINUV1 = false;
  82436. _this.MAINUV2 = false;
  82437. _this.UV1 = false;
  82438. _this.UV2 = false;
  82439. _this.CLIPPLANE = false;
  82440. _this.POINTSIZE = false;
  82441. _this.FOG = false;
  82442. _this.NORMAL = false;
  82443. _this.NUM_BONE_INFLUENCERS = 0;
  82444. _this.BonesPerMesh = 0;
  82445. _this.INSTANCES = false;
  82446. _this.SHADOWFLOAT = false;
  82447. _this.rebuild();
  82448. return _this;
  82449. }
  82450. return BackgroundMaterialDefines;
  82451. }(BABYLON.MaterialDefines));
  82452. /**
  82453. * Background material used to create an efficient environement around your scene.
  82454. */
  82455. var BackgroundMaterial = /** @class */ (function (_super) {
  82456. __extends(BackgroundMaterial, _super);
  82457. /**
  82458. * constructor
  82459. * @param name The name of the material
  82460. * @param scene The scene to add the material to
  82461. */
  82462. function BackgroundMaterial(name, scene) {
  82463. var _this = _super.call(this, name, scene) || this;
  82464. _this.primaryColor = BABYLON.Color3.White();
  82465. _this.primaryLevel = 1;
  82466. _this.secondaryColor = BABYLON.Color3.Gray();
  82467. _this.secondaryLevel = 1;
  82468. _this.tertiaryColor = BABYLON.Color3.Black();
  82469. _this.tertiaryLevel = 1;
  82470. _this.reflectionTexture = null;
  82471. _this.reflectionBlur = 0;
  82472. _this.diffuseTexture = null;
  82473. /**
  82474. * Specify the list of lights casting shadow on the material.
  82475. * All scene shadow lights will be included if null.
  82476. */
  82477. _this._shadowLights = null;
  82478. _this.shadowLights = null;
  82479. _this.shadowBlurScale = 1;
  82480. _this.shadowLevel = 0;
  82481. _this.sceneCenter = BABYLON.Vector3.Zero();
  82482. _this.opacityFresnel = true;
  82483. _this.reflectionFresnel = false;
  82484. _this.reflectionFalloffDistance = 0.0;
  82485. _this.reflectionAmount = 1.0;
  82486. _this.reflectionReflectance0 = 0.05;
  82487. _this.reflectionReflectance90 = 0.5;
  82488. _this.useRGBColor = true;
  82489. _this.enableNoise = false;
  82490. /**
  82491. * Number of Simultaneous lights allowed on the material.
  82492. */
  82493. _this._maxSimultaneousLights = 4;
  82494. _this.maxSimultaneousLights = 4;
  82495. /**
  82496. * Keep track of the image processing observer to allow dispose and replace.
  82497. */
  82498. _this._imageProcessingObserver = null;
  82499. // Temp values kept as cache in the material.
  82500. _this._renderTargets = new BABYLON.SmartArray(16);
  82501. _this._reflectionControls = BABYLON.Vector4.Zero();
  82502. // Setup the default processing configuration to the scene.
  82503. _this._attachImageProcessingConfiguration(null);
  82504. _this.getRenderTargetTextures = function () {
  82505. _this._renderTargets.reset();
  82506. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  82507. _this._renderTargets.push(_this._diffuseTexture);
  82508. }
  82509. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  82510. _this._renderTargets.push(_this._reflectionTexture);
  82511. }
  82512. return _this._renderTargets;
  82513. };
  82514. return _this;
  82515. }
  82516. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  82517. /**
  82518. * Sets the reflection reflectance fresnel values according to the default standard
  82519. * empirically know to work well :-)
  82520. */
  82521. set: function (value) {
  82522. var reflectionWeight = value;
  82523. if (reflectionWeight < 0.5) {
  82524. reflectionWeight = reflectionWeight * 2.0;
  82525. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  82526. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  82527. }
  82528. else {
  82529. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  82530. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  82531. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  82532. }
  82533. },
  82534. enumerable: true,
  82535. configurable: true
  82536. });
  82537. /**
  82538. * Attaches a new image processing configuration to the PBR Material.
  82539. * @param configuration (if null the scene configuration will be use)
  82540. */
  82541. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  82542. var _this = this;
  82543. if (configuration === this._imageProcessingConfiguration) {
  82544. return;
  82545. }
  82546. // Detaches observer.
  82547. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82548. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82549. }
  82550. // Pick the scene configuration if needed.
  82551. if (!configuration) {
  82552. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  82553. }
  82554. else {
  82555. this._imageProcessingConfiguration = configuration;
  82556. }
  82557. // Attaches observer.
  82558. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82559. _this._markAllSubMeshesAsImageProcessingDirty();
  82560. });
  82561. };
  82562. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  82563. /**
  82564. * Gets the image processing configuration used either in this material.
  82565. */
  82566. get: function () {
  82567. return this._imageProcessingConfiguration;
  82568. },
  82569. /**
  82570. * Sets the Default image processing configuration used either in the this material.
  82571. *
  82572. * If sets to null, the scene one is in use.
  82573. */
  82574. set: function (value) {
  82575. this._attachImageProcessingConfiguration(value);
  82576. // Ensure the effect will be rebuilt.
  82577. this._markAllSubMeshesAsTexturesDirty();
  82578. },
  82579. enumerable: true,
  82580. configurable: true
  82581. });
  82582. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  82583. /**
  82584. * Gets wether the color curves effect is enabled.
  82585. */
  82586. get: function () {
  82587. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82588. },
  82589. /**
  82590. * Sets wether the color curves effect is enabled.
  82591. */
  82592. set: function (value) {
  82593. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82594. },
  82595. enumerable: true,
  82596. configurable: true
  82597. });
  82598. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  82599. /**
  82600. * Gets wether the color grading effect is enabled.
  82601. */
  82602. get: function () {
  82603. return this.imageProcessingConfiguration.colorGradingEnabled;
  82604. },
  82605. /**
  82606. * Gets wether the color grading effect is enabled.
  82607. */
  82608. set: function (value) {
  82609. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82610. },
  82611. enumerable: true,
  82612. configurable: true
  82613. });
  82614. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  82615. /**
  82616. * Gets wether tonemapping is enabled or not.
  82617. */
  82618. get: function () {
  82619. return this._imageProcessingConfiguration.toneMappingEnabled;
  82620. },
  82621. /**
  82622. * Sets wether tonemapping is enabled or not
  82623. */
  82624. set: function (value) {
  82625. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82626. },
  82627. enumerable: true,
  82628. configurable: true
  82629. });
  82630. ;
  82631. ;
  82632. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  82633. /**
  82634. * The camera exposure used on this material.
  82635. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82636. * This corresponds to a photographic exposure.
  82637. */
  82638. get: function () {
  82639. return this._imageProcessingConfiguration.exposure;
  82640. },
  82641. /**
  82642. * The camera exposure used on this material.
  82643. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82644. * This corresponds to a photographic exposure.
  82645. */
  82646. set: function (value) {
  82647. this._imageProcessingConfiguration.exposure = value;
  82648. },
  82649. enumerable: true,
  82650. configurable: true
  82651. });
  82652. ;
  82653. ;
  82654. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  82655. /**
  82656. * Gets The camera contrast used on this material.
  82657. */
  82658. get: function () {
  82659. return this._imageProcessingConfiguration.contrast;
  82660. },
  82661. /**
  82662. * Sets The camera contrast used on this material.
  82663. */
  82664. set: function (value) {
  82665. this._imageProcessingConfiguration.contrast = value;
  82666. },
  82667. enumerable: true,
  82668. configurable: true
  82669. });
  82670. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  82671. /**
  82672. * Gets the Color Grading 2D Lookup Texture.
  82673. */
  82674. get: function () {
  82675. return this._imageProcessingConfiguration.colorGradingTexture;
  82676. },
  82677. /**
  82678. * Sets the Color Grading 2D Lookup Texture.
  82679. */
  82680. set: function (value) {
  82681. this.imageProcessingConfiguration.colorGradingTexture = value;
  82682. },
  82683. enumerable: true,
  82684. configurable: true
  82685. });
  82686. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  82687. /**
  82688. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82689. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82690. * 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;
  82691. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82692. */
  82693. get: function () {
  82694. return this.imageProcessingConfiguration.colorCurves;
  82695. },
  82696. /**
  82697. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82698. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82699. * 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;
  82700. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82701. */
  82702. set: function (value) {
  82703. this.imageProcessingConfiguration.colorCurves = value;
  82704. },
  82705. enumerable: true,
  82706. configurable: true
  82707. });
  82708. /**
  82709. * The entire material has been created in order to prevent overdraw.
  82710. * @returns false
  82711. */
  82712. BackgroundMaterial.prototype.needAlphaTesting = function () {
  82713. return true;
  82714. };
  82715. /**
  82716. * The entire material has been created in order to prevent overdraw.
  82717. * @returns true if blending is enable
  82718. */
  82719. BackgroundMaterial.prototype.needAlphaBlending = function () {
  82720. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  82721. };
  82722. /**
  82723. * Checks wether the material is ready to be rendered for a given mesh.
  82724. * @param mesh The mesh to render
  82725. * @param subMesh The submesh to check against
  82726. * @param useInstances Specify wether or not the material is used with instances
  82727. */
  82728. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  82729. var _this = this;
  82730. if (useInstances === void 0) { useInstances = false; }
  82731. if (subMesh.effect && this.isFrozen) {
  82732. if (this._wasPreviouslyReady) {
  82733. return true;
  82734. }
  82735. }
  82736. if (!subMesh._materialDefines) {
  82737. subMesh._materialDefines = new BackgroundMaterialDefines();
  82738. }
  82739. var scene = this.getScene();
  82740. var defines = subMesh._materialDefines;
  82741. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  82742. if (defines._renderId === scene.getRenderId()) {
  82743. return true;
  82744. }
  82745. }
  82746. var engine = scene.getEngine();
  82747. // Lights
  82748. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  82749. defines._needNormals = true;
  82750. // Textures
  82751. if (defines._areTexturesDirty) {
  82752. defines._needUVs = false;
  82753. if (scene.texturesEnabled) {
  82754. if (scene.getEngine().getCaps().textureLOD) {
  82755. defines.TEXTURELODSUPPORT = true;
  82756. }
  82757. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82758. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  82759. return false;
  82760. }
  82761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  82762. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  82763. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  82764. defines.OPACITYFRESNEL = this._opacityFresnel;
  82765. }
  82766. else {
  82767. defines.DIFFUSE = false;
  82768. defines.DIFFUSEHASALPHA = false;
  82769. defines.GAMMADIFFUSE = false;
  82770. defines.OPACITYFRESNEL = false;
  82771. }
  82772. var reflectionTexture = this._reflectionTexture;
  82773. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82774. if (!reflectionTexture.isReadyOrNotBlocking()) {
  82775. return false;
  82776. }
  82777. defines.REFLECTION = true;
  82778. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  82779. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  82780. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  82781. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  82782. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  82783. defines.INVERTCUBICMAP = true;
  82784. }
  82785. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  82786. switch (reflectionTexture.coordinatesMode) {
  82787. case BABYLON.Texture.CUBIC_MODE:
  82788. case BABYLON.Texture.INVCUBIC_MODE:
  82789. defines.REFLECTIONMAP_CUBIC = true;
  82790. break;
  82791. case BABYLON.Texture.EXPLICIT_MODE:
  82792. defines.REFLECTIONMAP_EXPLICIT = true;
  82793. break;
  82794. case BABYLON.Texture.PLANAR_MODE:
  82795. defines.REFLECTIONMAP_PLANAR = true;
  82796. break;
  82797. case BABYLON.Texture.PROJECTION_MODE:
  82798. defines.REFLECTIONMAP_PROJECTION = true;
  82799. break;
  82800. case BABYLON.Texture.SKYBOX_MODE:
  82801. defines.REFLECTIONMAP_SKYBOX = true;
  82802. break;
  82803. case BABYLON.Texture.SPHERICAL_MODE:
  82804. defines.REFLECTIONMAP_SPHERICAL = true;
  82805. break;
  82806. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  82807. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  82808. break;
  82809. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  82810. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  82811. break;
  82812. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  82813. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  82814. break;
  82815. }
  82816. if (this.reflectionFresnel) {
  82817. defines.REFLECTIONFRESNEL = true;
  82818. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  82819. this._reflectionControls.x = this.reflectionAmount;
  82820. this._reflectionControls.y = this.reflectionReflectance0;
  82821. this._reflectionControls.z = this.reflectionReflectance90;
  82822. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  82823. }
  82824. else {
  82825. defines.REFLECTIONFRESNEL = false;
  82826. defines.REFLECTIONFALLOFF = false;
  82827. }
  82828. }
  82829. else {
  82830. defines.REFLECTION = false;
  82831. defines.REFLECTIONFALLOFF = false;
  82832. defines.REFLECTIONBLUR = false;
  82833. defines.REFLECTIONMAP_3D = false;
  82834. defines.REFLECTIONMAP_SPHERICAL = false;
  82835. defines.REFLECTIONMAP_PLANAR = false;
  82836. defines.REFLECTIONMAP_CUBIC = false;
  82837. defines.REFLECTIONMAP_PROJECTION = false;
  82838. defines.REFLECTIONMAP_SKYBOX = false;
  82839. defines.REFLECTIONMAP_EXPLICIT = false;
  82840. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82841. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82842. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82843. defines.INVERTCUBICMAP = false;
  82844. defines.REFLECTIONMAP_OPPOSITEZ = false;
  82845. defines.LODINREFLECTIONALPHA = false;
  82846. defines.GAMMAREFLECTION = false;
  82847. }
  82848. }
  82849. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  82850. defines.USERGBCOLOR = this._useRGBColor;
  82851. defines.NOISE = this._enableNoise;
  82852. }
  82853. if (defines._areImageProcessingDirty) {
  82854. if (!this._imageProcessingConfiguration.isReady()) {
  82855. return false;
  82856. }
  82857. this._imageProcessingConfiguration.prepareDefines(defines);
  82858. }
  82859. // Misc.
  82860. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  82861. // Values that need to be evaluated on every frame
  82862. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  82863. // Attribs
  82864. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  82865. if (mesh) {
  82866. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  82867. mesh.createNormals(true);
  82868. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  82869. }
  82870. }
  82871. }
  82872. // Get correct effect
  82873. if (defines.isDirty) {
  82874. defines.markAsProcessed();
  82875. scene.resetCachedMaterial();
  82876. // Fallbacks
  82877. var fallbacks = new BABYLON.EffectFallbacks();
  82878. if (defines.FOG) {
  82879. fallbacks.addFallback(0, "FOG");
  82880. }
  82881. if (defines.POINTSIZE) {
  82882. fallbacks.addFallback(1, "POINTSIZE");
  82883. }
  82884. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  82885. if (defines.NUM_BONE_INFLUENCERS > 0) {
  82886. fallbacks.addCPUSkinningFallback(0, mesh);
  82887. }
  82888. //Attributes
  82889. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82890. if (defines.NORMAL) {
  82891. attribs.push(BABYLON.VertexBuffer.NormalKind);
  82892. }
  82893. if (defines.UV1) {
  82894. attribs.push(BABYLON.VertexBuffer.UVKind);
  82895. }
  82896. if (defines.UV2) {
  82897. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82898. }
  82899. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  82900. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  82901. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  82902. "vFogInfos", "vFogColor", "pointSize",
  82903. "vClipPlane", "mBones",
  82904. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  82905. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  82906. "shadowLevel", "alpha",
  82907. "vBackgroundCenter", "vReflectionControl",
  82908. "vDiffuseInfos", "diffuseMatrix",
  82909. ];
  82910. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  82911. var uniformBuffers = ["Material", "Scene"];
  82912. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  82913. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  82914. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  82915. uniformsNames: uniforms,
  82916. uniformBuffersNames: uniformBuffers,
  82917. samplers: samplers,
  82918. defines: defines,
  82919. maxSimultaneousLights: this._maxSimultaneousLights
  82920. });
  82921. var onCompiled = function (effect) {
  82922. if (_this.onCompiled) {
  82923. _this.onCompiled(effect);
  82924. }
  82925. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  82926. };
  82927. var join = defines.toString();
  82928. subMesh.setEffect(scene.getEngine().createEffect("background", {
  82929. attributes: attribs,
  82930. uniformsNames: uniforms,
  82931. uniformBuffersNames: uniformBuffers,
  82932. samplers: samplers,
  82933. defines: join,
  82934. fallbacks: fallbacks,
  82935. onCompiled: onCompiled,
  82936. onError: this.onError,
  82937. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  82938. }, engine), defines);
  82939. this.buildUniformLayout();
  82940. }
  82941. if (!subMesh.effect || !subMesh.effect.isReady()) {
  82942. return false;
  82943. }
  82944. defines._renderId = scene.getRenderId();
  82945. this._wasPreviouslyReady = true;
  82946. return true;
  82947. };
  82948. /**
  82949. * Build the uniform buffer used in the material.
  82950. */
  82951. BackgroundMaterial.prototype.buildUniformLayout = function () {
  82952. // Order is important !
  82953. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  82954. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  82955. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  82956. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  82957. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  82958. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  82959. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  82960. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  82961. this._uniformBuffer.addUniform("pointSize", 1);
  82962. this._uniformBuffer.addUniform("shadowLevel", 1);
  82963. this._uniformBuffer.addUniform("alpha", 1);
  82964. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  82965. this._uniformBuffer.addUniform("vReflectionControl", 4);
  82966. this._uniformBuffer.create();
  82967. };
  82968. /**
  82969. * Unbind the material.
  82970. */
  82971. BackgroundMaterial.prototype.unbind = function () {
  82972. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  82973. this._uniformBuffer.setTexture("diffuseSampler", null);
  82974. }
  82975. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  82976. this._uniformBuffer.setTexture("reflectionSampler", null);
  82977. }
  82978. _super.prototype.unbind.call(this);
  82979. };
  82980. /**
  82981. * Bind only the world matrix to the material.
  82982. * @param world The world matrix to bind.
  82983. */
  82984. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  82985. this._activeEffect.setMatrix("world", world);
  82986. };
  82987. /**
  82988. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  82989. * @param world The world matrix to bind.
  82990. * @param subMesh The submesh to bind for.
  82991. */
  82992. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  82993. var scene = this.getScene();
  82994. var defines = subMesh._materialDefines;
  82995. if (!defines) {
  82996. return;
  82997. }
  82998. var effect = subMesh.effect;
  82999. if (!effect) {
  83000. return;
  83001. }
  83002. this._activeEffect = effect;
  83003. // Matrices
  83004. this.bindOnlyWorldMatrix(world);
  83005. // Bones
  83006. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  83007. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  83008. if (mustRebind) {
  83009. this._uniformBuffer.bindToEffect(effect, "Material");
  83010. this.bindViewProjection(effect);
  83011. var reflectionTexture = this._reflectionTexture;
  83012. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  83013. // Texture uniforms
  83014. if (scene.texturesEnabled) {
  83015. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83016. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  83017. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  83018. }
  83019. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83020. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  83021. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  83022. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  83023. }
  83024. }
  83025. if (this.shadowLevel > 0) {
  83026. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  83027. }
  83028. this._uniformBuffer.updateFloat("alpha", this.alpha);
  83029. // Point size
  83030. if (this.pointsCloud) {
  83031. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  83032. }
  83033. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  83034. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  83035. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  83036. }
  83037. // Textures
  83038. if (scene.texturesEnabled) {
  83039. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83040. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  83041. }
  83042. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83043. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  83044. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83045. }
  83046. else if (!defines.REFLECTIONBLUR) {
  83047. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83048. }
  83049. else {
  83050. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  83051. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  83052. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  83053. }
  83054. if (defines.REFLECTIONFRESNEL) {
  83055. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  83056. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  83057. }
  83058. }
  83059. }
  83060. // Clip plane
  83061. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  83062. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  83063. }
  83064. if (mustRebind || !this.isFrozen) {
  83065. if (scene.lightsEnabled) {
  83066. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  83067. }
  83068. // View
  83069. this.bindView(effect);
  83070. // Fog
  83071. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83072. // image processing
  83073. this._imageProcessingConfiguration.bind(this._activeEffect);
  83074. }
  83075. this._uniformBuffer.update();
  83076. this._afterBind(mesh);
  83077. };
  83078. /**
  83079. * Dispose the material.
  83080. * @forceDisposeEffect Force disposal of the associated effect.
  83081. * @forceDisposeTextures Force disposal of the associated textures.
  83082. */
  83083. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  83084. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  83085. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  83086. if (forceDisposeTextures) {
  83087. if (this.diffuseTexture) {
  83088. this.diffuseTexture.dispose();
  83089. }
  83090. if (this.reflectionTexture) {
  83091. this.reflectionTexture.dispose();
  83092. }
  83093. }
  83094. this._renderTargets.dispose();
  83095. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83096. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83097. }
  83098. _super.prototype.dispose.call(this, forceDisposeEffect);
  83099. };
  83100. /**
  83101. * Clones the material.
  83102. * @name The cloned name.
  83103. * @returns The cloned material.
  83104. */
  83105. BackgroundMaterial.prototype.clone = function (name) {
  83106. var _this = this;
  83107. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  83108. };
  83109. /**
  83110. * Serializes the current material to its JSON representation.
  83111. * @returns The JSON representation.
  83112. */
  83113. BackgroundMaterial.prototype.serialize = function () {
  83114. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83115. serializationObject.customType = "BABYLON.BackgroundMaterial";
  83116. return serializationObject;
  83117. };
  83118. /**
  83119. * Gets the class name of the material
  83120. * @returns "BackgroundMaterial"
  83121. */
  83122. BackgroundMaterial.prototype.getClassName = function () {
  83123. return "BackgroundMaterial";
  83124. };
  83125. /**
  83126. * Parse a JSON input to create back a background material.
  83127. * @param source
  83128. * @param scene
  83129. * @param rootUrl
  83130. * @returns the instantiated BackgroundMaterial.
  83131. */
  83132. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  83133. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  83134. };
  83135. /**
  83136. * Standard reflectance value at parallel view angle.
  83137. */
  83138. BackgroundMaterial.standardReflectance0 = 0.05;
  83139. /**
  83140. * Standard reflectance value at grazing angle.
  83141. */
  83142. BackgroundMaterial.standardReflectance90 = 0.5;
  83143. __decorate([
  83144. BABYLON.serializeAsColor3()
  83145. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  83146. __decorate([
  83147. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83148. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  83149. __decorate([
  83150. BABYLON.serialize()
  83151. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  83152. __decorate([
  83153. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83154. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  83155. __decorate([
  83156. BABYLON.serializeAsColor3()
  83157. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  83158. __decorate([
  83159. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83160. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  83161. __decorate([
  83162. BABYLON.serialize()
  83163. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  83164. __decorate([
  83165. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83166. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  83167. __decorate([
  83168. BABYLON.serializeAsColor3()
  83169. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  83170. __decorate([
  83171. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83172. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  83173. __decorate([
  83174. BABYLON.serialize()
  83175. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  83176. __decorate([
  83177. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83178. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  83179. __decorate([
  83180. BABYLON.serializeAsTexture()
  83181. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  83182. __decorate([
  83183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83184. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  83185. __decorate([
  83186. BABYLON.serialize()
  83187. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  83188. __decorate([
  83189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83190. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  83191. __decorate([
  83192. BABYLON.serializeAsTexture()
  83193. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  83194. __decorate([
  83195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83196. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  83197. __decorate([
  83198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83199. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  83200. __decorate([
  83201. BABYLON.serialize()
  83202. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  83203. __decorate([
  83204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83205. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  83206. __decorate([
  83207. BABYLON.serialize()
  83208. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  83209. __decorate([
  83210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83211. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  83212. __decorate([
  83213. BABYLON.serializeAsVector3()
  83214. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  83215. __decorate([
  83216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83217. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  83218. __decorate([
  83219. BABYLON.serialize()
  83220. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  83221. __decorate([
  83222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83223. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  83224. __decorate([
  83225. BABYLON.serialize()
  83226. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  83227. __decorate([
  83228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83229. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  83230. __decorate([
  83231. BABYLON.serialize()
  83232. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  83233. __decorate([
  83234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83235. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  83236. __decorate([
  83237. BABYLON.serialize()
  83238. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  83239. __decorate([
  83240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83241. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  83242. __decorate([
  83243. BABYLON.serialize()
  83244. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  83245. __decorate([
  83246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83247. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  83248. __decorate([
  83249. BABYLON.serialize()
  83250. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  83251. __decorate([
  83252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83253. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  83254. __decorate([
  83255. BABYLON.serialize()
  83256. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  83257. __decorate([
  83258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83259. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  83260. __decorate([
  83261. BABYLON.serialize()
  83262. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  83263. __decorate([
  83264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83265. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  83266. __decorate([
  83267. BABYLON.serialize()
  83268. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  83269. __decorate([
  83270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83271. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  83272. __decorate([
  83273. BABYLON.serializeAsImageProcessingConfiguration()
  83274. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  83275. return BackgroundMaterial;
  83276. }(BABYLON.PushMaterial));
  83277. BABYLON.BackgroundMaterial = BackgroundMaterial;
  83278. })(BABYLON || (BABYLON = {}));
  83279. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  83280. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83281. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83282. s = arguments[i];
  83283. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83284. t[p] = s[p];
  83285. }
  83286. return t;
  83287. };
  83288. var BABYLON;
  83289. (function (BABYLON) {
  83290. /**
  83291. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  83292. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  83293. * It also helps with the default setup of your imageProcessing configuration.
  83294. */
  83295. var EnvironmentHelper = /** @class */ (function () {
  83296. /**
  83297. * constructor
  83298. * @param options
  83299. * @param scene The scene to add the material to
  83300. */
  83301. function EnvironmentHelper(options, scene) {
  83302. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  83303. this._scene = scene;
  83304. this._setupBackground();
  83305. this._setupImageProcessing();
  83306. }
  83307. /**
  83308. * Creates the default options for the helper.
  83309. */
  83310. EnvironmentHelper._getDefaultOptions = function () {
  83311. return {
  83312. createGround: true,
  83313. groundSize: 15,
  83314. groundTexture: this._groundTextureCDNUrl,
  83315. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83316. groundOpacity: 0.9,
  83317. enableGroundShadow: true,
  83318. groundShadowLevel: 0.5,
  83319. enableGroundMirror: false,
  83320. groundMirrorSizeRatio: 0.3,
  83321. groundMirrorBlurKernel: 64,
  83322. groundMirrorAmount: 1,
  83323. groundMirrorFresnelWeight: 1,
  83324. groundMirrorFallOffDistance: 0,
  83325. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  83326. groundYBias: 0.00001,
  83327. createSkybox: true,
  83328. skyboxSize: 20,
  83329. skyboxTexture: this._skyboxTextureCDNUrl,
  83330. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83331. backgroundYRotation: 0,
  83332. sizeAuto: true,
  83333. rootPosition: BABYLON.Vector3.Zero(),
  83334. setupImageProcessing: true,
  83335. environmentTexture: this._environmentTextureCDNUrl,
  83336. cameraExposure: 0.8,
  83337. cameraContrast: 1.2,
  83338. toneMappingEnabled: true,
  83339. };
  83340. };
  83341. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  83342. /**
  83343. * Gets the root mesh created by the helper.
  83344. */
  83345. get: function () {
  83346. return this._rootMesh;
  83347. },
  83348. enumerable: true,
  83349. configurable: true
  83350. });
  83351. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  83352. /**
  83353. * Gets the skybox created by the helper.
  83354. */
  83355. get: function () {
  83356. return this._skybox;
  83357. },
  83358. enumerable: true,
  83359. configurable: true
  83360. });
  83361. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  83362. /**
  83363. * Gets the skybox texture created by the helper.
  83364. */
  83365. get: function () {
  83366. return this._skyboxTexture;
  83367. },
  83368. enumerable: true,
  83369. configurable: true
  83370. });
  83371. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  83372. /**
  83373. * Gets the skybox material created by the helper.
  83374. */
  83375. get: function () {
  83376. return this._skyboxMaterial;
  83377. },
  83378. enumerable: true,
  83379. configurable: true
  83380. });
  83381. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  83382. /**
  83383. * Gets the ground mesh created by the helper.
  83384. */
  83385. get: function () {
  83386. return this._ground;
  83387. },
  83388. enumerable: true,
  83389. configurable: true
  83390. });
  83391. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  83392. /**
  83393. * Gets the ground texture created by the helper.
  83394. */
  83395. get: function () {
  83396. return this._groundTexture;
  83397. },
  83398. enumerable: true,
  83399. configurable: true
  83400. });
  83401. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  83402. /**
  83403. * Gets the ground mirror created by the helper.
  83404. */
  83405. get: function () {
  83406. return this._groundMirror;
  83407. },
  83408. enumerable: true,
  83409. configurable: true
  83410. });
  83411. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  83412. /**
  83413. * Gets the ground mirror render list to helps pushing the meshes
  83414. * you wish in the ground reflection.
  83415. */
  83416. get: function () {
  83417. if (this._groundMirror) {
  83418. return this._groundMirror.renderList;
  83419. }
  83420. return null;
  83421. },
  83422. enumerable: true,
  83423. configurable: true
  83424. });
  83425. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  83426. /**
  83427. * Gets the ground material created by the helper.
  83428. */
  83429. get: function () {
  83430. return this._groundMaterial;
  83431. },
  83432. enumerable: true,
  83433. configurable: true
  83434. });
  83435. /**
  83436. * Updates the background according to the new options
  83437. * @param options
  83438. */
  83439. EnvironmentHelper.prototype.updateOptions = function (options) {
  83440. var newOptions = __assign({}, this._options, options);
  83441. if (this._ground && !newOptions.createGround) {
  83442. this._ground.dispose();
  83443. this._ground = null;
  83444. }
  83445. if (this._groundMaterial && !newOptions.createGround) {
  83446. this._groundMaterial.dispose();
  83447. this._groundMaterial = null;
  83448. }
  83449. if (this._groundTexture) {
  83450. if (this._options.groundTexture != newOptions.groundTexture) {
  83451. this._groundTexture.dispose();
  83452. this._groundTexture = null;
  83453. }
  83454. }
  83455. if (this._skybox && !newOptions.createSkybox) {
  83456. this._skybox.dispose();
  83457. this._skybox = null;
  83458. }
  83459. if (this._skyboxMaterial && !newOptions.createSkybox) {
  83460. this._skyboxMaterial.dispose();
  83461. this._skyboxMaterial = null;
  83462. }
  83463. if (this._skyboxTexture) {
  83464. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  83465. this._skyboxTexture.dispose();
  83466. this._skyboxTexture = null;
  83467. }
  83468. }
  83469. if (this._groundMirror && !newOptions.enableGroundMirror) {
  83470. this._groundMirror.dispose();
  83471. this._groundMirror = null;
  83472. }
  83473. if (this._scene.environmentTexture) {
  83474. if (this._options.environmentTexture != newOptions.environmentTexture) {
  83475. this._scene.environmentTexture.dispose();
  83476. }
  83477. }
  83478. this._options = newOptions;
  83479. this._setupBackground();
  83480. this._setupImageProcessing();
  83481. };
  83482. /**
  83483. * Sets the primary color of all the available elements.
  83484. * @param color
  83485. */
  83486. EnvironmentHelper.prototype.setMainColor = function (color) {
  83487. if (this.groundMaterial) {
  83488. this.groundMaterial.primaryColor = color;
  83489. }
  83490. if (this.skyboxMaterial) {
  83491. this.skyboxMaterial.primaryColor = color;
  83492. }
  83493. if (this.groundMirror) {
  83494. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  83495. }
  83496. };
  83497. /**
  83498. * Setup the image processing according to the specified options.
  83499. */
  83500. EnvironmentHelper.prototype._setupImageProcessing = function () {
  83501. if (this._options.setupImageProcessing) {
  83502. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  83503. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  83504. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  83505. this._setupEnvironmentTexture();
  83506. }
  83507. };
  83508. /**
  83509. * Setup the environment texture according to the specified options.
  83510. */
  83511. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  83512. if (this._scene.environmentTexture) {
  83513. return;
  83514. }
  83515. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  83516. this._scene.environmentTexture = this._options.environmentTexture;
  83517. return;
  83518. }
  83519. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  83520. this._scene.environmentTexture = environmentTexture;
  83521. };
  83522. /**
  83523. * Setup the background according to the specified options.
  83524. */
  83525. EnvironmentHelper.prototype._setupBackground = function () {
  83526. if (!this._rootMesh) {
  83527. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  83528. }
  83529. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  83530. var sceneSize = this._getSceneSize();
  83531. if (this._options.createGround) {
  83532. this._setupGround(sceneSize);
  83533. this._setupGroundMaterial();
  83534. this._setupGroundDiffuseTexture();
  83535. if (this._options.enableGroundMirror) {
  83536. this._setupGroundMirrorTexture(sceneSize);
  83537. }
  83538. this._setupMirrorInGroundMaterial();
  83539. }
  83540. if (this._options.createSkybox) {
  83541. this._setupSkybox(sceneSize);
  83542. this._setupSkyboxMaterial();
  83543. this._setupSkyboxReflectionTexture();
  83544. }
  83545. this._rootMesh.position.x = sceneSize.rootPosition.x;
  83546. this._rootMesh.position.z = sceneSize.rootPosition.z;
  83547. this._rootMesh.position.y = sceneSize.rootPosition.y;
  83548. };
  83549. /**
  83550. * Get the scene sizes according to the setup.
  83551. */
  83552. EnvironmentHelper.prototype._getSceneSize = function () {
  83553. var groundSize = this._options.groundSize;
  83554. var skyboxSize = this._options.skyboxSize;
  83555. var rootPosition = this._options.rootPosition;
  83556. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  83557. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83558. }
  83559. var sceneExtends = this._scene.getWorldExtends();
  83560. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  83561. if (this._options.sizeAuto) {
  83562. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  83563. this._scene.activeCamera.upperRadiusLimit) {
  83564. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  83565. skyboxSize = groundSize;
  83566. }
  83567. var sceneDiagonalLenght = sceneDiagonal.length();
  83568. if (sceneDiagonalLenght > groundSize) {
  83569. groundSize = sceneDiagonalLenght * 2;
  83570. skyboxSize = groundSize;
  83571. }
  83572. // 10 % bigger.
  83573. groundSize *= 1.1;
  83574. skyboxSize *= 1.5;
  83575. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  83576. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  83577. }
  83578. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83579. };
  83580. /**
  83581. * Setup the ground according to the specified options.
  83582. */
  83583. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  83584. var _this = this;
  83585. if (!this._ground) {
  83586. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  83587. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  83588. this._ground.parent = this._rootMesh;
  83589. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  83590. }
  83591. this._ground.receiveShadows = this._options.enableGroundShadow;
  83592. };
  83593. /**
  83594. * Setup the ground material according to the specified options.
  83595. */
  83596. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  83597. if (!this._groundMaterial) {
  83598. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  83599. }
  83600. this._groundMaterial.alpha = this._options.groundOpacity;
  83601. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  83602. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  83603. this._groundMaterial.primaryLevel = 1;
  83604. this._groundMaterial.primaryColor = this._options.groundColor;
  83605. this._groundMaterial.secondaryLevel = 0;
  83606. this._groundMaterial.tertiaryLevel = 0;
  83607. this._groundMaterial.useRGBColor = false;
  83608. this._groundMaterial.enableNoise = true;
  83609. if (this._ground) {
  83610. this._ground.material = this._groundMaterial;
  83611. }
  83612. };
  83613. /**
  83614. * Setup the ground diffuse texture according to the specified options.
  83615. */
  83616. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  83617. if (!this._groundMaterial) {
  83618. return;
  83619. }
  83620. if (this._groundTexture) {
  83621. return;
  83622. }
  83623. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  83624. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  83625. return;
  83626. }
  83627. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  83628. diffuseTexture.gammaSpace = false;
  83629. diffuseTexture.hasAlpha = true;
  83630. this._groundMaterial.diffuseTexture = diffuseTexture;
  83631. };
  83632. /**
  83633. * Setup the ground mirror texture according to the specified options.
  83634. */
  83635. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  83636. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83637. if (!this._groundMirror) {
  83638. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  83639. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  83640. this._groundMirror.anisotropicFilteringLevel = 1;
  83641. this._groundMirror.wrapU = wrapping;
  83642. this._groundMirror.wrapV = wrapping;
  83643. this._groundMirror.gammaSpace = false;
  83644. if (this._groundMirror.renderList) {
  83645. for (var i = 0; i < this._scene.meshes.length; i++) {
  83646. var mesh = this._scene.meshes[i];
  83647. if (mesh !== this._ground &&
  83648. mesh !== this._skybox &&
  83649. mesh !== this._rootMesh) {
  83650. this._groundMirror.renderList.push(mesh);
  83651. }
  83652. }
  83653. }
  83654. }
  83655. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  83656. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  83657. };
  83658. /**
  83659. * Setup the ground to receive the mirror texture.
  83660. */
  83661. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  83662. if (this._groundMaterial) {
  83663. this._groundMaterial.reflectionTexture = this._groundMirror;
  83664. this._groundMaterial.reflectionFresnel = true;
  83665. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  83666. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  83667. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  83668. }
  83669. };
  83670. /**
  83671. * Setup the skybox according to the specified options.
  83672. */
  83673. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  83674. var _this = this;
  83675. if (!this._skybox) {
  83676. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  83677. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  83678. }
  83679. this._skybox.parent = this._rootMesh;
  83680. };
  83681. /**
  83682. * Setup the skybox material according to the specified options.
  83683. */
  83684. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  83685. if (!this._skybox) {
  83686. return;
  83687. }
  83688. if (!this._skyboxMaterial) {
  83689. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  83690. }
  83691. this._skyboxMaterial.useRGBColor = false;
  83692. this._skyboxMaterial.primaryLevel = 1;
  83693. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  83694. this._skyboxMaterial.secondaryLevel = 0;
  83695. this._skyboxMaterial.tertiaryLevel = 0;
  83696. this._skyboxMaterial.enableNoise = true;
  83697. this._skybox.material = this._skyboxMaterial;
  83698. };
  83699. /**
  83700. * Setup the skybox reflection texture according to the specified options.
  83701. */
  83702. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  83703. if (!this._skyboxMaterial) {
  83704. return;
  83705. }
  83706. if (this._skyboxTexture) {
  83707. return;
  83708. }
  83709. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  83710. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83711. return;
  83712. }
  83713. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  83714. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  83715. this._skyboxTexture.gammaSpace = false;
  83716. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83717. };
  83718. /**
  83719. * Dispose all the elements created by the Helper.
  83720. */
  83721. EnvironmentHelper.prototype.dispose = function () {
  83722. if (this._groundMaterial) {
  83723. this._groundMaterial.dispose(true, true);
  83724. }
  83725. if (this._skyboxMaterial) {
  83726. this._skyboxMaterial.dispose(true, true);
  83727. }
  83728. this._rootMesh.dispose(false);
  83729. };
  83730. /**
  83731. * Default ground texture URL.
  83732. */
  83733. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  83734. /**
  83735. * Default skybox texture URL.
  83736. */
  83737. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  83738. /**
  83739. * Default environment texture URL.
  83740. */
  83741. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  83742. return EnvironmentHelper;
  83743. }());
  83744. BABYLON.EnvironmentHelper = EnvironmentHelper;
  83745. })(BABYLON || (BABYLON = {}));
  83746. //# sourceMappingURL=babylon.environmentHelper.js.map
  83747. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","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);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\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","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>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  83748. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#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};","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","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  83749. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  83750. var BABYLON;
  83751. (function (BABYLON) {
  83752. var GridMaterialDefines = /** @class */ (function (_super) {
  83753. __extends(GridMaterialDefines, _super);
  83754. function GridMaterialDefines() {
  83755. var _this = _super.call(this) || this;
  83756. _this.TRANSPARENT = false;
  83757. _this.FOG = false;
  83758. _this.PREMULTIPLYALPHA = false;
  83759. _this.rebuild();
  83760. return _this;
  83761. }
  83762. return GridMaterialDefines;
  83763. }(BABYLON.MaterialDefines));
  83764. /**
  83765. * The grid materials allows you to wrap any shape with a grid.
  83766. * Colors are customizable.
  83767. */
  83768. var GridMaterial = /** @class */ (function (_super) {
  83769. __extends(GridMaterial, _super);
  83770. /**
  83771. * constructor
  83772. * @param name The name given to the material in order to identify it afterwards.
  83773. * @param scene The scene the material is used in.
  83774. */
  83775. function GridMaterial(name, scene) {
  83776. var _this = _super.call(this, name, scene) || this;
  83777. /**
  83778. * Main color of the grid (e.g. between lines)
  83779. */
  83780. _this.mainColor = BABYLON.Color3.Black();
  83781. /**
  83782. * Color of the grid lines.
  83783. */
  83784. _this.lineColor = BABYLON.Color3.Teal();
  83785. /**
  83786. * The scale of the grid compared to unit.
  83787. */
  83788. _this.gridRatio = 1.0;
  83789. /**
  83790. * Allows setting an offset for the grid lines.
  83791. */
  83792. _this.gridOffset = BABYLON.Vector3.Zero();
  83793. /**
  83794. * The frequency of thicker lines.
  83795. */
  83796. _this.majorUnitFrequency = 10;
  83797. /**
  83798. * The visibility of minor units in the grid.
  83799. */
  83800. _this.minorUnitVisibility = 0.33;
  83801. /**
  83802. * The grid opacity outside of the lines.
  83803. */
  83804. _this.opacity = 1.0;
  83805. /**
  83806. * Determine RBG output is premultiplied by alpha value.
  83807. */
  83808. _this.preMultiplyAlpha = false;
  83809. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  83810. return _this;
  83811. }
  83812. /**
  83813. * Returns wehter or not the grid requires alpha blending.
  83814. */
  83815. GridMaterial.prototype.needAlphaBlending = function () {
  83816. return this.opacity < 1.0;
  83817. };
  83818. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  83819. return this.needAlphaBlending();
  83820. };
  83821. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83822. if (this.isFrozen) {
  83823. if (this._wasPreviouslyReady && subMesh.effect) {
  83824. return true;
  83825. }
  83826. }
  83827. if (!subMesh._materialDefines) {
  83828. subMesh._materialDefines = new GridMaterialDefines();
  83829. }
  83830. var defines = subMesh._materialDefines;
  83831. var scene = this.getScene();
  83832. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  83833. if (this._renderId === scene.getRenderId()) {
  83834. return true;
  83835. }
  83836. }
  83837. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  83838. defines.TRANSPARENT = !defines.TRANSPARENT;
  83839. defines.markAsUnprocessed();
  83840. }
  83841. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  83842. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  83843. defines.markAsUnprocessed();
  83844. }
  83845. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  83846. // Get correct effect
  83847. if (defines.isDirty) {
  83848. defines.markAsProcessed();
  83849. scene.resetCachedMaterial();
  83850. // Attributes
  83851. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83852. // Defines
  83853. var join = defines.toString();
  83854. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  83855. }
  83856. if (!subMesh.effect || !subMesh.effect.isReady()) {
  83857. return false;
  83858. }
  83859. this._renderId = scene.getRenderId();
  83860. this._wasPreviouslyReady = true;
  83861. return true;
  83862. };
  83863. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  83864. var scene = this.getScene();
  83865. var defines = subMesh._materialDefines;
  83866. if (!defines) {
  83867. return;
  83868. }
  83869. var effect = subMesh.effect;
  83870. if (!effect) {
  83871. return;
  83872. }
  83873. this._activeEffect = effect;
  83874. // Matrices
  83875. this.bindOnlyWorldMatrix(world);
  83876. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  83877. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  83878. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  83879. // Uniforms
  83880. if (this._mustRebind(scene, effect)) {
  83881. this._activeEffect.setColor3("mainColor", this.mainColor);
  83882. this._activeEffect.setColor3("lineColor", this.lineColor);
  83883. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  83884. this._gridControl.x = this.gridRatio;
  83885. this._gridControl.y = Math.round(this.majorUnitFrequency);
  83886. this._gridControl.z = this.minorUnitVisibility;
  83887. this._gridControl.w = this.opacity;
  83888. this._activeEffect.setVector4("gridControl", this._gridControl);
  83889. }
  83890. // Fog
  83891. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83892. this._afterBind(mesh, this._activeEffect);
  83893. };
  83894. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  83895. _super.prototype.dispose.call(this, forceDisposeEffect);
  83896. };
  83897. GridMaterial.prototype.clone = function (name) {
  83898. var _this = this;
  83899. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  83900. };
  83901. GridMaterial.prototype.serialize = function () {
  83902. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83903. serializationObject.customType = "BABYLON.GridMaterial";
  83904. return serializationObject;
  83905. };
  83906. GridMaterial.prototype.getClassName = function () {
  83907. return "GridMaterial";
  83908. };
  83909. GridMaterial.Parse = function (source, scene, rootUrl) {
  83910. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  83911. };
  83912. __decorate([
  83913. BABYLON.serializeAsColor3()
  83914. ], GridMaterial.prototype, "mainColor", void 0);
  83915. __decorate([
  83916. BABYLON.serializeAsColor3()
  83917. ], GridMaterial.prototype, "lineColor", void 0);
  83918. __decorate([
  83919. BABYLON.serialize()
  83920. ], GridMaterial.prototype, "gridRatio", void 0);
  83921. __decorate([
  83922. BABYLON.serializeAsColor3()
  83923. ], GridMaterial.prototype, "gridOffset", void 0);
  83924. __decorate([
  83925. BABYLON.serialize()
  83926. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  83927. __decorate([
  83928. BABYLON.serialize()
  83929. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  83930. __decorate([
  83931. BABYLON.serialize()
  83932. ], GridMaterial.prototype, "opacity", void 0);
  83933. __decorate([
  83934. BABYLON.serialize()
  83935. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  83936. return GridMaterial;
  83937. }(BABYLON.PushMaterial));
  83938. BABYLON.GridMaterial = GridMaterial;
  83939. })(BABYLON || (BABYLON = {}));
  83940. //# sourceMappingURL=babylon.gridmaterial.js.map
  83941. 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}";
  83942. 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}";
  83943. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  83944. var BABYLON;
  83945. (function (BABYLON) {
  83946. var GLTFLoaderCoordinateSystemMode;
  83947. (function (GLTFLoaderCoordinateSystemMode) {
  83948. /**
  83949. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  83950. */
  83951. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  83952. /**
  83953. * Sets the useRightHandedSystem flag on the scene.
  83954. */
  83955. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  83956. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  83957. var GLTFLoaderAnimationStartMode;
  83958. (function (GLTFLoaderAnimationStartMode) {
  83959. /**
  83960. * No animation will start.
  83961. */
  83962. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  83963. /**
  83964. * The first animation will start.
  83965. */
  83966. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  83967. /**
  83968. * All animations will start.
  83969. */
  83970. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  83971. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  83972. var GLTFFileLoader = /** @class */ (function () {
  83973. function GLTFFileLoader() {
  83974. // #region Common options
  83975. /**
  83976. * Raised when the asset has been parsed.
  83977. * The data.json property stores the glTF JSON.
  83978. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  83979. */
  83980. this.onParsedObservable = new BABYLON.Observable();
  83981. // #endregion
  83982. // #region V2 options
  83983. /**
  83984. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  83985. */
  83986. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  83987. /**
  83988. * The animation start mode (NONE, FIRST, ALL).
  83989. */
  83990. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  83991. /**
  83992. * Set to true to compile materials before raising the success callback.
  83993. */
  83994. this.compileMaterials = false;
  83995. /**
  83996. * Set to true to also compile materials with clip planes.
  83997. */
  83998. this.useClipPlane = false;
  83999. /**
  84000. * Set to true to compile shadow generators before raising the success callback.
  84001. */
  84002. this.compileShadowGenerators = false;
  84003. /**
  84004. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  84005. */
  84006. this.onMeshLoadedObservable = new BABYLON.Observable();
  84007. /**
  84008. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  84009. */
  84010. this.onTextureLoadedObservable = new BABYLON.Observable();
  84011. /**
  84012. * Raised when the loader creates a material after parsing the glTF properties of the material.
  84013. */
  84014. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84015. /**
  84016. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  84017. * For assets with LODs, raised when all of the LODs are complete.
  84018. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  84019. */
  84020. this.onCompleteObservable = new BABYLON.Observable();
  84021. /**
  84022. * Raised when the loader is disposed.
  84023. */
  84024. this.onDisposeObservable = new BABYLON.Observable();
  84025. // #endregion
  84026. this._loader = null;
  84027. this.name = "gltf";
  84028. this.extensions = {
  84029. ".gltf": { isBinary: false },
  84030. ".glb": { isBinary: true }
  84031. };
  84032. }
  84033. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  84034. set: function (callback) {
  84035. if (this._onParsedObserver) {
  84036. this.onParsedObservable.remove(this._onParsedObserver);
  84037. }
  84038. this._onParsedObserver = this.onParsedObservable.add(callback);
  84039. },
  84040. enumerable: true,
  84041. configurable: true
  84042. });
  84043. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  84044. set: function (callback) {
  84045. if (this._onMeshLoadedObserver) {
  84046. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  84047. }
  84048. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  84049. },
  84050. enumerable: true,
  84051. configurable: true
  84052. });
  84053. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  84054. set: function (callback) {
  84055. if (this._onTextureLoadedObserver) {
  84056. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  84057. }
  84058. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  84059. },
  84060. enumerable: true,
  84061. configurable: true
  84062. });
  84063. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  84064. set: function (callback) {
  84065. if (this._onMaterialLoadedObserver) {
  84066. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  84067. }
  84068. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  84069. },
  84070. enumerable: true,
  84071. configurable: true
  84072. });
  84073. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  84074. set: function (callback) {
  84075. if (this._onCompleteObserver) {
  84076. this.onCompleteObservable.remove(this._onCompleteObserver);
  84077. }
  84078. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  84079. },
  84080. enumerable: true,
  84081. configurable: true
  84082. });
  84083. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  84084. set: function (callback) {
  84085. if (this._onDisposeObserver) {
  84086. this.onDisposeObservable.remove(this._onDisposeObserver);
  84087. }
  84088. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84089. },
  84090. enumerable: true,
  84091. configurable: true
  84092. });
  84093. /**
  84094. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  84095. */
  84096. GLTFFileLoader.prototype.dispose = function () {
  84097. if (this._loader) {
  84098. this._loader.dispose();
  84099. this._loader = null;
  84100. }
  84101. this.onParsedObservable.clear();
  84102. this.onMeshLoadedObservable.clear();
  84103. this.onTextureLoadedObservable.clear();
  84104. this.onMaterialLoadedObservable.clear();
  84105. this.onCompleteObservable.clear();
  84106. this.onDisposeObservable.notifyObservers(this);
  84107. this.onDisposeObservable.clear();
  84108. };
  84109. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84110. try {
  84111. var loaderData = this._parse(data);
  84112. this._loader = this._getLoader(loaderData);
  84113. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  84114. }
  84115. catch (e) {
  84116. if (onError) {
  84117. onError(e.message, e);
  84118. }
  84119. else {
  84120. BABYLON.Tools.Error(e.message);
  84121. }
  84122. }
  84123. };
  84124. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84125. try {
  84126. var loaderData = this._parse(data);
  84127. this._loader = this._getLoader(loaderData);
  84128. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  84129. }
  84130. catch (e) {
  84131. if (onError) {
  84132. onError(e.message, e);
  84133. }
  84134. else {
  84135. BABYLON.Tools.Error(e.message);
  84136. }
  84137. }
  84138. };
  84139. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84140. try {
  84141. var loaderData = this._parse(data);
  84142. this._loader = this._getLoader(loaderData);
  84143. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  84144. var container = new BABYLON.AssetContainer(scene);
  84145. Array.prototype.push.apply(container.meshes, meshes);
  84146. Array.prototype.push.apply(container.particleSystems, particleSystems);
  84147. Array.prototype.push.apply(container.skeletons, skeletons);
  84148. container.removeAllFromScene();
  84149. onSuccess(container);
  84150. }, onProgress, onError);
  84151. }
  84152. catch (e) {
  84153. if (onError) {
  84154. onError(e.message, e);
  84155. }
  84156. else {
  84157. BABYLON.Tools.Error(e.message);
  84158. }
  84159. }
  84160. };
  84161. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  84162. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  84163. };
  84164. GLTFFileLoader.prototype.createPlugin = function () {
  84165. return new GLTFFileLoader();
  84166. };
  84167. GLTFFileLoader.prototype._parse = function (data) {
  84168. var parsedData;
  84169. if (data instanceof ArrayBuffer) {
  84170. parsedData = GLTFFileLoader._parseBinary(data);
  84171. }
  84172. else {
  84173. parsedData = {
  84174. json: JSON.parse(data),
  84175. bin: null
  84176. };
  84177. }
  84178. this.onParsedObservable.notifyObservers(parsedData);
  84179. return parsedData;
  84180. };
  84181. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  84182. var _this = this;
  84183. var loaderVersion = { major: 2, minor: 0 };
  84184. var asset = loaderData.json.asset || {};
  84185. var version = GLTFFileLoader._parseVersion(asset.version);
  84186. if (!version) {
  84187. throw new Error("Invalid version: " + asset.version);
  84188. }
  84189. if (asset.minVersion !== undefined) {
  84190. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  84191. if (!minVersion) {
  84192. throw new Error("Invalid minimum version: " + asset.minVersion);
  84193. }
  84194. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  84195. throw new Error("Incompatible minimum version: " + asset.minVersion);
  84196. }
  84197. }
  84198. var createLoaders = {
  84199. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  84200. 2: GLTFFileLoader.CreateGLTFLoaderV2
  84201. };
  84202. var createLoader = createLoaders[version.major];
  84203. if (!createLoader) {
  84204. throw new Error("Unsupported version: " + asset.version);
  84205. }
  84206. var loader = createLoader();
  84207. loader.coordinateSystemMode = this.coordinateSystemMode;
  84208. loader.animationStartMode = this.animationStartMode;
  84209. loader.compileMaterials = this.compileMaterials;
  84210. loader.useClipPlane = this.useClipPlane;
  84211. loader.compileShadowGenerators = this.compileShadowGenerators;
  84212. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  84213. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  84214. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  84215. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  84216. return loader;
  84217. };
  84218. GLTFFileLoader._parseBinary = function (data) {
  84219. var Binary = {
  84220. Magic: 0x46546C67
  84221. };
  84222. var binaryReader = new BinaryReader(data);
  84223. var magic = binaryReader.readUint32();
  84224. if (magic !== Binary.Magic) {
  84225. throw new Error("Unexpected magic: " + magic);
  84226. }
  84227. var version = binaryReader.readUint32();
  84228. switch (version) {
  84229. case 1: return GLTFFileLoader._parseV1(binaryReader);
  84230. case 2: return GLTFFileLoader._parseV2(binaryReader);
  84231. }
  84232. throw new Error("Unsupported version: " + version);
  84233. };
  84234. GLTFFileLoader._parseV1 = function (binaryReader) {
  84235. var ContentFormat = {
  84236. JSON: 0
  84237. };
  84238. var length = binaryReader.readUint32();
  84239. if (length != binaryReader.getLength()) {
  84240. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  84241. }
  84242. var contentLength = binaryReader.readUint32();
  84243. var contentFormat = binaryReader.readUint32();
  84244. var content;
  84245. switch (contentFormat) {
  84246. case ContentFormat.JSON: {
  84247. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  84248. break;
  84249. }
  84250. default: {
  84251. throw new Error("Unexpected content format: " + contentFormat);
  84252. }
  84253. }
  84254. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  84255. var body = binaryReader.readUint8Array(bytesRemaining);
  84256. return {
  84257. json: content,
  84258. bin: body
  84259. };
  84260. };
  84261. GLTFFileLoader._parseV2 = function (binaryReader) {
  84262. var ChunkFormat = {
  84263. JSON: 0x4E4F534A,
  84264. BIN: 0x004E4942
  84265. };
  84266. var length = binaryReader.readUint32();
  84267. if (length !== binaryReader.getLength()) {
  84268. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  84269. }
  84270. // JSON chunk
  84271. var chunkLength = binaryReader.readUint32();
  84272. var chunkFormat = binaryReader.readUint32();
  84273. if (chunkFormat !== ChunkFormat.JSON) {
  84274. throw new Error("First chunk format is not JSON");
  84275. }
  84276. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  84277. // Look for BIN chunk
  84278. var bin = null;
  84279. while (binaryReader.getPosition() < binaryReader.getLength()) {
  84280. var chunkLength_1 = binaryReader.readUint32();
  84281. var chunkFormat_1 = binaryReader.readUint32();
  84282. switch (chunkFormat_1) {
  84283. case ChunkFormat.JSON: {
  84284. throw new Error("Unexpected JSON chunk");
  84285. }
  84286. case ChunkFormat.BIN: {
  84287. bin = binaryReader.readUint8Array(chunkLength_1);
  84288. break;
  84289. }
  84290. default: {
  84291. // ignore unrecognized chunkFormat
  84292. binaryReader.skipBytes(chunkLength_1);
  84293. break;
  84294. }
  84295. }
  84296. }
  84297. return {
  84298. json: json,
  84299. bin: bin
  84300. };
  84301. };
  84302. GLTFFileLoader._parseVersion = function (version) {
  84303. if (version === "1.0" || version === "1.0.1") {
  84304. return {
  84305. major: 1,
  84306. minor: 0
  84307. };
  84308. }
  84309. var match = (version + "").match(/^(\d+)\.(\d+)/);
  84310. if (!match) {
  84311. return null;
  84312. }
  84313. return {
  84314. major: parseInt(match[1]),
  84315. minor: parseInt(match[2])
  84316. };
  84317. };
  84318. GLTFFileLoader._compareVersion = function (a, b) {
  84319. if (a.major > b.major)
  84320. return 1;
  84321. if (a.major < b.major)
  84322. return -1;
  84323. if (a.minor > b.minor)
  84324. return 1;
  84325. if (a.minor < b.minor)
  84326. return -1;
  84327. return 0;
  84328. };
  84329. GLTFFileLoader._decodeBufferToText = function (buffer) {
  84330. var result = "";
  84331. var length = buffer.byteLength;
  84332. for (var i = 0; i < length; i++) {
  84333. result += String.fromCharCode(buffer[i]);
  84334. }
  84335. return result;
  84336. };
  84337. // #endregion
  84338. // #region V1 options
  84339. GLTFFileLoader.IncrementalLoading = true;
  84340. GLTFFileLoader.HomogeneousCoordinates = false;
  84341. return GLTFFileLoader;
  84342. }());
  84343. BABYLON.GLTFFileLoader = GLTFFileLoader;
  84344. var BinaryReader = /** @class */ (function () {
  84345. function BinaryReader(arrayBuffer) {
  84346. this._arrayBuffer = arrayBuffer;
  84347. this._dataView = new DataView(arrayBuffer);
  84348. this._byteOffset = 0;
  84349. }
  84350. BinaryReader.prototype.getPosition = function () {
  84351. return this._byteOffset;
  84352. };
  84353. BinaryReader.prototype.getLength = function () {
  84354. return this._arrayBuffer.byteLength;
  84355. };
  84356. BinaryReader.prototype.readUint32 = function () {
  84357. var value = this._dataView.getUint32(this._byteOffset, true);
  84358. this._byteOffset += 4;
  84359. return value;
  84360. };
  84361. BinaryReader.prototype.readUint8Array = function (length) {
  84362. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  84363. this._byteOffset += length;
  84364. return value;
  84365. };
  84366. BinaryReader.prototype.skipBytes = function (length) {
  84367. this._byteOffset += length;
  84368. };
  84369. return BinaryReader;
  84370. }());
  84371. if (BABYLON.SceneLoader) {
  84372. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  84373. }
  84374. })(BABYLON || (BABYLON = {}));
  84375. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  84376. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84377. var BABYLON;
  84378. (function (BABYLON) {
  84379. var GLTF1;
  84380. (function (GLTF1) {
  84381. /**
  84382. * Enums
  84383. */
  84384. var EComponentType;
  84385. (function (EComponentType) {
  84386. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84387. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84388. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84389. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84390. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84391. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  84392. var EShaderType;
  84393. (function (EShaderType) {
  84394. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  84395. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  84396. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  84397. var EParameterType;
  84398. (function (EParameterType) {
  84399. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  84400. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84401. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  84402. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84403. EParameterType[EParameterType["INT"] = 5124] = "INT";
  84404. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84405. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  84406. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  84407. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  84408. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  84409. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  84410. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  84411. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  84412. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  84413. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  84414. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  84415. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  84416. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  84417. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  84418. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  84419. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  84420. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  84421. var ETextureWrapMode;
  84422. (function (ETextureWrapMode) {
  84423. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84424. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84425. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84426. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  84427. var ETextureFilterType;
  84428. (function (ETextureFilterType) {
  84429. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  84430. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  84431. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84432. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84433. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84434. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84435. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  84436. var ETextureFormat;
  84437. (function (ETextureFormat) {
  84438. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  84439. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  84440. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  84441. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  84442. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  84443. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  84444. var ECullingType;
  84445. (function (ECullingType) {
  84446. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  84447. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  84448. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  84449. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  84450. var EBlendingFunction;
  84451. (function (EBlendingFunction) {
  84452. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  84453. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  84454. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  84455. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  84456. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  84457. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  84458. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  84459. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  84460. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  84461. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  84462. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  84463. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  84464. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  84465. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  84466. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  84467. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  84468. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84469. })(BABYLON || (BABYLON = {}));
  84470. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84471. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84472. var BABYLON;
  84473. (function (BABYLON) {
  84474. var GLTF1;
  84475. (function (GLTF1) {
  84476. /**
  84477. * Tokenizer. Used for shaders compatibility
  84478. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  84479. */
  84480. var ETokenType;
  84481. (function (ETokenType) {
  84482. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  84483. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  84484. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  84485. })(ETokenType || (ETokenType = {}));
  84486. var Tokenizer = /** @class */ (function () {
  84487. function Tokenizer(toParse) {
  84488. this._pos = 0;
  84489. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  84490. this._toParse = toParse;
  84491. this._maxPos = toParse.length;
  84492. }
  84493. Tokenizer.prototype.getNextToken = function () {
  84494. if (this.isEnd())
  84495. return ETokenType.END_OF_INPUT;
  84496. this.currentString = this.read();
  84497. this.currentToken = ETokenType.UNKNOWN;
  84498. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  84499. this.currentToken = ETokenType.IDENTIFIER;
  84500. this.currentIdentifier = this.currentString;
  84501. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  84502. this.currentIdentifier += this.currentString;
  84503. this.forward();
  84504. }
  84505. }
  84506. return this.currentToken;
  84507. };
  84508. Tokenizer.prototype.peek = function () {
  84509. return this._toParse[this._pos];
  84510. };
  84511. Tokenizer.prototype.read = function () {
  84512. return this._toParse[this._pos++];
  84513. };
  84514. Tokenizer.prototype.forward = function () {
  84515. this._pos++;
  84516. };
  84517. Tokenizer.prototype.isEnd = function () {
  84518. return this._pos >= this._maxPos;
  84519. };
  84520. return Tokenizer;
  84521. }());
  84522. /**
  84523. * Values
  84524. */
  84525. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  84526. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  84527. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  84528. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  84529. /**
  84530. * Parse
  84531. */
  84532. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  84533. for (var buf in parsedBuffers) {
  84534. var parsedBuffer = parsedBuffers[buf];
  84535. gltfRuntime.buffers[buf] = parsedBuffer;
  84536. gltfRuntime.buffersCount++;
  84537. }
  84538. };
  84539. var parseShaders = function (parsedShaders, gltfRuntime) {
  84540. for (var sha in parsedShaders) {
  84541. var parsedShader = parsedShaders[sha];
  84542. gltfRuntime.shaders[sha] = parsedShader;
  84543. gltfRuntime.shaderscount++;
  84544. }
  84545. };
  84546. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  84547. for (var object in parsedObjects) {
  84548. var parsedObject = parsedObjects[object];
  84549. gltfRuntime[runtimeProperty][object] = parsedObject;
  84550. }
  84551. };
  84552. /**
  84553. * Utils
  84554. */
  84555. var normalizeUVs = function (buffer) {
  84556. if (!buffer) {
  84557. return;
  84558. }
  84559. for (var i = 0; i < buffer.length / 2; i++) {
  84560. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  84561. }
  84562. };
  84563. var getAttribute = function (attributeParameter) {
  84564. if (attributeParameter.semantic === "NORMAL") {
  84565. return "normal";
  84566. }
  84567. else if (attributeParameter.semantic === "POSITION") {
  84568. return "position";
  84569. }
  84570. else if (attributeParameter.semantic === "JOINT") {
  84571. return "matricesIndices";
  84572. }
  84573. else if (attributeParameter.semantic === "WEIGHT") {
  84574. return "matricesWeights";
  84575. }
  84576. else if (attributeParameter.semantic === "COLOR") {
  84577. return "color";
  84578. }
  84579. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  84580. var channel = Number(attributeParameter.semantic.split("_")[1]);
  84581. return "uv" + (channel === 0 ? "" : channel + 1);
  84582. }
  84583. return null;
  84584. };
  84585. /**
  84586. * Loads and creates animations
  84587. */
  84588. var loadAnimations = function (gltfRuntime) {
  84589. for (var anim in gltfRuntime.animations) {
  84590. var animation = gltfRuntime.animations[anim];
  84591. if (!animation.channels || !animation.samplers) {
  84592. continue;
  84593. }
  84594. var lastAnimation = null;
  84595. for (var i = 0; i < animation.channels.length; i++) {
  84596. // Get parameters and load buffers
  84597. var channel = animation.channels[i];
  84598. var sampler = animation.samplers[channel.sampler];
  84599. if (!sampler) {
  84600. continue;
  84601. }
  84602. var inputData = null;
  84603. var outputData = null;
  84604. if (animation.parameters) {
  84605. inputData = animation.parameters[sampler.input];
  84606. outputData = animation.parameters[sampler.output];
  84607. }
  84608. else {
  84609. inputData = sampler.input;
  84610. outputData = sampler.output;
  84611. }
  84612. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  84613. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  84614. var targetID = channel.target.id;
  84615. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  84616. if (targetNode === null) {
  84617. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  84618. }
  84619. if (targetNode === null) {
  84620. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  84621. continue;
  84622. }
  84623. var isBone = targetNode instanceof BABYLON.Bone;
  84624. // Get target path (position, rotation or scaling)
  84625. var targetPath = channel.target.path;
  84626. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  84627. if (targetPathIndex !== -1) {
  84628. targetPath = babylonAnimationPaths[targetPathIndex];
  84629. }
  84630. // Determine animation type
  84631. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  84632. if (!isBone) {
  84633. if (targetPath === "rotationQuaternion") {
  84634. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  84635. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  84636. }
  84637. else {
  84638. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  84639. }
  84640. }
  84641. // Create animation and key frames
  84642. var babylonAnimation = null;
  84643. var keys = [];
  84644. var arrayOffset = 0;
  84645. var modifyKey = false;
  84646. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  84647. babylonAnimation = lastAnimation;
  84648. modifyKey = true;
  84649. }
  84650. if (!modifyKey) {
  84651. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  84652. }
  84653. // For each frame
  84654. for (var j = 0; j < bufferInput.length; j++) {
  84655. var value = null;
  84656. if (targetPath === "rotationQuaternion") {
  84657. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  84658. arrayOffset += 4;
  84659. }
  84660. else {
  84661. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  84662. arrayOffset += 3;
  84663. }
  84664. if (isBone) {
  84665. var bone = targetNode;
  84666. var translation = BABYLON.Vector3.Zero();
  84667. var rotationQuaternion = new BABYLON.Quaternion();
  84668. var scaling = BABYLON.Vector3.Zero();
  84669. // Warning on decompose
  84670. var mat = bone.getBaseMatrix();
  84671. if (modifyKey && lastAnimation) {
  84672. mat = lastAnimation.getKeys()[j].value;
  84673. }
  84674. mat.decompose(scaling, rotationQuaternion, translation);
  84675. if (targetPath === "position") {
  84676. translation = value;
  84677. }
  84678. else if (targetPath === "rotationQuaternion") {
  84679. rotationQuaternion = value;
  84680. }
  84681. else {
  84682. scaling = value;
  84683. }
  84684. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  84685. }
  84686. if (!modifyKey) {
  84687. keys.push({
  84688. frame: bufferInput[j],
  84689. value: value
  84690. });
  84691. }
  84692. else if (lastAnimation) {
  84693. lastAnimation.getKeys()[j].value = value;
  84694. }
  84695. }
  84696. // Finish
  84697. if (!modifyKey && babylonAnimation) {
  84698. babylonAnimation.setKeys(keys);
  84699. targetNode.animations.push(babylonAnimation);
  84700. }
  84701. lastAnimation = babylonAnimation;
  84702. gltfRuntime.scene.stopAnimation(targetNode);
  84703. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  84704. }
  84705. }
  84706. };
  84707. /**
  84708. * Returns the bones transformation matrix
  84709. */
  84710. var configureBoneTransformation = function (node) {
  84711. var mat = null;
  84712. if (node.translation || node.rotation || node.scale) {
  84713. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  84714. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  84715. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  84716. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  84717. }
  84718. else {
  84719. mat = BABYLON.Matrix.FromArray(node.matrix);
  84720. }
  84721. return mat;
  84722. };
  84723. /**
  84724. * Returns the parent bone
  84725. */
  84726. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  84727. // Try to find
  84728. for (var i = 0; i < newSkeleton.bones.length; i++) {
  84729. if (newSkeleton.bones[i].name === jointName) {
  84730. return newSkeleton.bones[i];
  84731. }
  84732. }
  84733. // Not found, search in gltf nodes
  84734. var nodes = gltfRuntime.nodes;
  84735. for (var nde in nodes) {
  84736. var node = nodes[nde];
  84737. if (!node.jointName) {
  84738. continue;
  84739. }
  84740. var children = node.children;
  84741. for (var i = 0; i < children.length; i++) {
  84742. var child = gltfRuntime.nodes[children[i]];
  84743. if (!child.jointName) {
  84744. continue;
  84745. }
  84746. if (child.jointName === jointName) {
  84747. var mat = configureBoneTransformation(node);
  84748. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  84749. bone.id = nde;
  84750. return bone;
  84751. }
  84752. }
  84753. }
  84754. return null;
  84755. };
  84756. /**
  84757. * Returns the appropriate root node
  84758. */
  84759. var getNodeToRoot = function (nodesToRoot, id) {
  84760. for (var i = 0; i < nodesToRoot.length; i++) {
  84761. var nodeToRoot = nodesToRoot[i];
  84762. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  84763. var child = nodeToRoot.node.children[j];
  84764. if (child === id) {
  84765. return nodeToRoot.bone;
  84766. }
  84767. }
  84768. }
  84769. return null;
  84770. };
  84771. /**
  84772. * Returns the node with the joint name
  84773. */
  84774. var getJointNode = function (gltfRuntime, jointName) {
  84775. var nodes = gltfRuntime.nodes;
  84776. var node = nodes[jointName];
  84777. if (node) {
  84778. return {
  84779. node: node,
  84780. id: jointName
  84781. };
  84782. }
  84783. for (var nde in nodes) {
  84784. node = nodes[nde];
  84785. if (node.jointName === jointName) {
  84786. return {
  84787. node: node,
  84788. id: nde
  84789. };
  84790. }
  84791. }
  84792. return null;
  84793. };
  84794. /**
  84795. * Checks if a nodes is in joints
  84796. */
  84797. var nodeIsInJoints = function (skins, id) {
  84798. for (var i = 0; i < skins.jointNames.length; i++) {
  84799. if (skins.jointNames[i] === id) {
  84800. return true;
  84801. }
  84802. }
  84803. return false;
  84804. };
  84805. /**
  84806. * Fills the nodes to root for bones and builds hierarchy
  84807. */
  84808. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  84809. // Creates nodes for root
  84810. for (var nde in gltfRuntime.nodes) {
  84811. var node = gltfRuntime.nodes[nde];
  84812. var id = nde;
  84813. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  84814. continue;
  84815. }
  84816. // Create node to root bone
  84817. var mat = configureBoneTransformation(node);
  84818. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  84819. bone.id = id;
  84820. nodesToRoot.push({ bone: bone, node: node, id: id });
  84821. }
  84822. // Parenting
  84823. for (var i = 0; i < nodesToRoot.length; i++) {
  84824. var nodeToRoot = nodesToRoot[i];
  84825. var children = nodeToRoot.node.children;
  84826. for (var j = 0; j < children.length; j++) {
  84827. var child = null;
  84828. for (var k = 0; k < nodesToRoot.length; k++) {
  84829. if (nodesToRoot[k].id === children[j]) {
  84830. child = nodesToRoot[k];
  84831. break;
  84832. }
  84833. }
  84834. if (child) {
  84835. child.bone._parent = nodeToRoot.bone;
  84836. nodeToRoot.bone.children.push(child.bone);
  84837. }
  84838. }
  84839. }
  84840. };
  84841. /**
  84842. * Imports a skeleton
  84843. */
  84844. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  84845. if (!newSkeleton) {
  84846. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  84847. }
  84848. if (!skins.babylonSkeleton) {
  84849. return newSkeleton;
  84850. }
  84851. // Find the root bones
  84852. var nodesToRoot = [];
  84853. var nodesToRootToAdd = [];
  84854. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  84855. newSkeleton.bones = [];
  84856. // Joints
  84857. for (var i = 0; i < skins.jointNames.length; i++) {
  84858. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  84859. if (!jointNode) {
  84860. continue;
  84861. }
  84862. var node = jointNode.node;
  84863. if (!node) {
  84864. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  84865. continue;
  84866. }
  84867. var id = jointNode.id;
  84868. // Optimize, if the bone already exists...
  84869. var existingBone = gltfRuntime.scene.getBoneByID(id);
  84870. if (existingBone) {
  84871. newSkeleton.bones.push(existingBone);
  84872. continue;
  84873. }
  84874. // Search for parent bone
  84875. var foundBone = false;
  84876. var parentBone = null;
  84877. for (var j = 0; j < i; j++) {
  84878. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  84879. if (!jointNode_1) {
  84880. continue;
  84881. }
  84882. var joint = jointNode_1.node;
  84883. if (!joint) {
  84884. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  84885. continue;
  84886. }
  84887. var children = joint.children;
  84888. if (!children) {
  84889. continue;
  84890. }
  84891. foundBone = false;
  84892. for (var k = 0; k < children.length; k++) {
  84893. if (children[k] === id) {
  84894. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  84895. foundBone = true;
  84896. break;
  84897. }
  84898. }
  84899. if (foundBone) {
  84900. break;
  84901. }
  84902. }
  84903. // Create bone
  84904. var mat = configureBoneTransformation(node);
  84905. if (!parentBone && nodesToRoot.length > 0) {
  84906. parentBone = getNodeToRoot(nodesToRoot, id);
  84907. if (parentBone) {
  84908. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  84909. nodesToRootToAdd.push(parentBone);
  84910. }
  84911. }
  84912. }
  84913. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  84914. bone.id = id;
  84915. }
  84916. // Polish
  84917. var bones = newSkeleton.bones;
  84918. newSkeleton.bones = [];
  84919. for (var i = 0; i < skins.jointNames.length; i++) {
  84920. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  84921. if (!jointNode) {
  84922. continue;
  84923. }
  84924. for (var j = 0; j < bones.length; j++) {
  84925. if (bones[j].id === jointNode.id) {
  84926. newSkeleton.bones.push(bones[j]);
  84927. break;
  84928. }
  84929. }
  84930. }
  84931. newSkeleton.prepare();
  84932. // Finish
  84933. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  84934. newSkeleton.bones.push(nodesToRootToAdd[i]);
  84935. }
  84936. return newSkeleton;
  84937. };
  84938. /**
  84939. * Imports a mesh and its geometries
  84940. */
  84941. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  84942. if (!newMesh) {
  84943. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  84944. newMesh.id = id;
  84945. }
  84946. if (!node.babylonNode) {
  84947. return newMesh;
  84948. }
  84949. var subMaterials = [];
  84950. var vertexData = new BABYLON.VertexData();
  84951. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  84952. var verticesStarts = new Array();
  84953. var verticesCounts = new Array();
  84954. var indexStarts = new Array();
  84955. var indexCounts = new Array();
  84956. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  84957. var meshID = meshes[meshIndex];
  84958. var mesh = gltfRuntime.meshes[meshID];
  84959. if (!mesh) {
  84960. continue;
  84961. }
  84962. // Positions, normals and UVs
  84963. for (var i = 0; i < mesh.primitives.length; i++) {
  84964. // Temporary vertex data
  84965. var tempVertexData = new BABYLON.VertexData();
  84966. var primitive = mesh.primitives[i];
  84967. if (primitive.mode !== 4) {
  84968. // continue;
  84969. }
  84970. var attributes = primitive.attributes;
  84971. var accessor = null;
  84972. var buffer = null;
  84973. // Set positions, normal and uvs
  84974. for (var semantic in attributes) {
  84975. // Link accessor and buffer view
  84976. accessor = gltfRuntime.accessors[attributes[semantic]];
  84977. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  84978. if (semantic === "NORMAL") {
  84979. tempVertexData.normals = new Float32Array(buffer.length);
  84980. tempVertexData.normals.set(buffer);
  84981. }
  84982. else if (semantic === "POSITION") {
  84983. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  84984. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  84985. for (var j = 0; j < buffer.length; j += 4) {
  84986. tempVertexData.positions[j] = buffer[j];
  84987. tempVertexData.positions[j + 1] = buffer[j + 1];
  84988. tempVertexData.positions[j + 2] = buffer[j + 2];
  84989. }
  84990. }
  84991. else {
  84992. tempVertexData.positions = new Float32Array(buffer.length);
  84993. tempVertexData.positions.set(buffer);
  84994. }
  84995. verticesCounts.push(tempVertexData.positions.length);
  84996. }
  84997. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  84998. var channel = Number(semantic.split("_")[1]);
  84999. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  85000. var uvs = new Float32Array(buffer.length);
  85001. uvs.set(buffer);
  85002. normalizeUVs(uvs);
  85003. tempVertexData.set(uvs, uvKind);
  85004. }
  85005. else if (semantic === "JOINT") {
  85006. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  85007. tempVertexData.matricesIndices.set(buffer);
  85008. }
  85009. else if (semantic === "WEIGHT") {
  85010. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  85011. tempVertexData.matricesWeights.set(buffer);
  85012. }
  85013. else if (semantic === "COLOR") {
  85014. tempVertexData.colors = new Float32Array(buffer.length);
  85015. tempVertexData.colors.set(buffer);
  85016. }
  85017. }
  85018. // Indices
  85019. accessor = gltfRuntime.accessors[primitive.indices];
  85020. if (accessor) {
  85021. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  85022. tempVertexData.indices = new Int32Array(buffer.length);
  85023. tempVertexData.indices.set(buffer);
  85024. indexCounts.push(tempVertexData.indices.length);
  85025. }
  85026. else {
  85027. // Set indices on the fly
  85028. var indices = [];
  85029. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  85030. indices.push(j);
  85031. }
  85032. tempVertexData.indices = new Int32Array(indices);
  85033. indexCounts.push(tempVertexData.indices.length);
  85034. }
  85035. vertexData.merge(tempVertexData);
  85036. // Sub material
  85037. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  85038. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  85039. // Update vertices start and index start
  85040. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  85041. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  85042. }
  85043. }
  85044. var material;
  85045. if (subMaterials.length > 1) {
  85046. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  85047. material.subMaterials = subMaterials;
  85048. }
  85049. else {
  85050. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  85051. }
  85052. if (subMaterials.length === 1) {
  85053. material = subMaterials[0];
  85054. }
  85055. if (!newMesh.material) {
  85056. newMesh.material = material;
  85057. }
  85058. // Apply geometry
  85059. geometry.setAllVerticesData(vertexData, false);
  85060. newMesh.computeWorldMatrix(true);
  85061. // Apply submeshes
  85062. newMesh.subMeshes = [];
  85063. var index = 0;
  85064. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  85065. var meshID = meshes[meshIndex];
  85066. var mesh = gltfRuntime.meshes[meshID];
  85067. if (!mesh) {
  85068. continue;
  85069. }
  85070. for (var i = 0; i < mesh.primitives.length; i++) {
  85071. if (mesh.primitives[i].mode !== 4) {
  85072. //continue;
  85073. }
  85074. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  85075. index++;
  85076. }
  85077. }
  85078. // Finish
  85079. return newMesh;
  85080. };
  85081. /**
  85082. * Configure node transformation from position, rotation and scaling
  85083. */
  85084. var configureNode = function (newNode, position, rotation, scaling) {
  85085. if (newNode.position) {
  85086. newNode.position = position;
  85087. }
  85088. if (newNode.rotationQuaternion || newNode.rotation) {
  85089. newNode.rotationQuaternion = rotation;
  85090. }
  85091. if (newNode.scaling) {
  85092. newNode.scaling = scaling;
  85093. }
  85094. };
  85095. /**
  85096. * Configures node from transformation matrix
  85097. */
  85098. var configureNodeFromMatrix = function (newNode, node, parent) {
  85099. if (node.matrix) {
  85100. var position = new BABYLON.Vector3(0, 0, 0);
  85101. var rotation = new BABYLON.Quaternion();
  85102. var scaling = new BABYLON.Vector3(0, 0, 0);
  85103. var mat = BABYLON.Matrix.FromArray(node.matrix);
  85104. mat.decompose(scaling, rotation, position);
  85105. configureNode(newNode, position, rotation, scaling);
  85106. }
  85107. else if (node.translation && node.rotation && node.scale) {
  85108. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  85109. }
  85110. newNode.computeWorldMatrix(true);
  85111. };
  85112. /**
  85113. * Imports a node
  85114. */
  85115. var importNode = function (gltfRuntime, node, id, parent) {
  85116. var lastNode = null;
  85117. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  85118. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  85119. return null;
  85120. }
  85121. }
  85122. // Meshes
  85123. if (node.skin) {
  85124. if (node.meshes) {
  85125. var skin = gltfRuntime.skins[node.skin];
  85126. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  85127. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  85128. if (newMesh.skeleton === null) {
  85129. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  85130. if (!skin.babylonSkeleton) {
  85131. skin.babylonSkeleton = newMesh.skeleton;
  85132. }
  85133. }
  85134. lastNode = newMesh;
  85135. }
  85136. }
  85137. else if (node.meshes) {
  85138. /**
  85139. * Improve meshes property
  85140. */
  85141. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  85142. lastNode = newMesh;
  85143. }
  85144. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  85145. var light = gltfRuntime.lights[node.light];
  85146. if (light) {
  85147. if (light.type === "ambient") {
  85148. var ambienLight = light[light.type];
  85149. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85150. hemiLight.name = node.name || "";
  85151. if (ambienLight.color) {
  85152. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  85153. }
  85154. lastNode = hemiLight;
  85155. }
  85156. else if (light.type === "directional") {
  85157. var directionalLight = light[light.type];
  85158. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85159. dirLight.name = node.name || "";
  85160. if (directionalLight.color) {
  85161. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  85162. }
  85163. lastNode = dirLight;
  85164. }
  85165. else if (light.type === "point") {
  85166. var pointLight = light[light.type];
  85167. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85168. ptLight.name = node.name || "";
  85169. if (pointLight.color) {
  85170. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  85171. }
  85172. lastNode = ptLight;
  85173. }
  85174. else if (light.type === "spot") {
  85175. var spotLight = light[light.type];
  85176. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  85177. spLight.name = node.name || "";
  85178. if (spotLight.color) {
  85179. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  85180. }
  85181. if (spotLight.fallOfAngle) {
  85182. spLight.angle = spotLight.fallOfAngle;
  85183. }
  85184. if (spotLight.fallOffExponent) {
  85185. spLight.exponent = spotLight.fallOffExponent;
  85186. }
  85187. lastNode = spLight;
  85188. }
  85189. }
  85190. }
  85191. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  85192. var camera = gltfRuntime.cameras[node.camera];
  85193. if (camera) {
  85194. if (camera.type === "orthographic") {
  85195. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85196. orthoCamera.name = node.name || "";
  85197. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  85198. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  85199. lastNode = orthoCamera;
  85200. }
  85201. else if (camera.type === "perspective") {
  85202. var perspectiveCamera = camera[camera.type];
  85203. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  85204. persCamera.name = node.name || "";
  85205. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  85206. if (!perspectiveCamera.aspectRatio) {
  85207. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  85208. }
  85209. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  85210. persCamera.maxZ = perspectiveCamera.zfar;
  85211. persCamera.minZ = perspectiveCamera.znear;
  85212. }
  85213. lastNode = persCamera;
  85214. }
  85215. }
  85216. }
  85217. // Empty node
  85218. if (!node.jointName) {
  85219. if (node.babylonNode) {
  85220. return node.babylonNode;
  85221. }
  85222. else if (lastNode === null) {
  85223. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  85224. node.babylonNode = dummy;
  85225. lastNode = dummy;
  85226. }
  85227. }
  85228. if (lastNode !== null) {
  85229. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  85230. configureNodeFromMatrix(lastNode, node, parent);
  85231. }
  85232. else {
  85233. var translation = node.translation || [0, 0, 0];
  85234. var rotation = node.rotation || [0, 0, 0, 1];
  85235. var scale = node.scale || [1, 1, 1];
  85236. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  85237. }
  85238. lastNode.updateCache(true);
  85239. node.babylonNode = lastNode;
  85240. }
  85241. return lastNode;
  85242. };
  85243. /**
  85244. * Traverses nodes and creates them
  85245. */
  85246. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  85247. if (meshIncluded === void 0) { meshIncluded = false; }
  85248. var node = gltfRuntime.nodes[id];
  85249. var newNode = null;
  85250. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  85251. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  85252. meshIncluded = true;
  85253. }
  85254. else {
  85255. meshIncluded = false;
  85256. }
  85257. }
  85258. else {
  85259. meshIncluded = true;
  85260. }
  85261. if (!node.jointName && meshIncluded) {
  85262. newNode = importNode(gltfRuntime, node, id, parent);
  85263. if (newNode !== null) {
  85264. newNode.id = id;
  85265. newNode.parent = parent;
  85266. }
  85267. }
  85268. if (node.children) {
  85269. for (var i = 0; i < node.children.length; i++) {
  85270. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  85271. }
  85272. }
  85273. };
  85274. /**
  85275. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  85276. */
  85277. var postLoad = function (gltfRuntime) {
  85278. // Nodes
  85279. var currentScene = gltfRuntime.currentScene;
  85280. if (currentScene) {
  85281. for (var i = 0; i < currentScene.nodes.length; i++) {
  85282. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85283. }
  85284. }
  85285. else {
  85286. for (var thing in gltfRuntime.scenes) {
  85287. currentScene = gltfRuntime.scenes[thing];
  85288. for (var i = 0; i < currentScene.nodes.length; i++) {
  85289. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85290. }
  85291. }
  85292. }
  85293. // Set animations
  85294. loadAnimations(gltfRuntime);
  85295. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  85296. var skeleton = gltfRuntime.scene.skeletons[i];
  85297. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  85298. }
  85299. };
  85300. /**
  85301. * onBind shaderrs callback to set uniforms and matrices
  85302. */
  85303. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  85304. var materialValues = material.values || technique.parameters;
  85305. for (var unif in unTreatedUniforms) {
  85306. var uniform = unTreatedUniforms[unif];
  85307. var type = uniform.type;
  85308. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  85309. if (uniform.semantic && !uniform.source && !uniform.node) {
  85310. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  85311. }
  85312. else if (uniform.semantic && (uniform.source || uniform.node)) {
  85313. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  85314. if (source === null) {
  85315. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  85316. }
  85317. if (source === null) {
  85318. continue;
  85319. }
  85320. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  85321. }
  85322. }
  85323. else {
  85324. var value = materialValues[technique.uniforms[unif]];
  85325. if (!value) {
  85326. continue;
  85327. }
  85328. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  85329. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  85330. if (texture === null || texture === undefined) {
  85331. continue;
  85332. }
  85333. shaderMaterial.getEffect().setTexture(unif, texture);
  85334. }
  85335. else {
  85336. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  85337. }
  85338. }
  85339. }
  85340. onSuccess(shaderMaterial);
  85341. };
  85342. /**
  85343. * Prepare uniforms to send the only one time
  85344. * Loads the appropriate textures
  85345. */
  85346. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  85347. var materialValues = material.values || technique.parameters;
  85348. var techniqueUniforms = technique.uniforms;
  85349. /**
  85350. * Prepare values here (not matrices)
  85351. */
  85352. for (var unif in unTreatedUniforms) {
  85353. var uniform = unTreatedUniforms[unif];
  85354. var type = uniform.type;
  85355. var value = materialValues[techniqueUniforms[unif]];
  85356. if (value === undefined) {
  85357. // In case the value is the same for all materials
  85358. value = uniform.value;
  85359. }
  85360. if (!value) {
  85361. continue;
  85362. }
  85363. var onLoadTexture = function (uniformName) {
  85364. return function (texture) {
  85365. if (uniform.value && uniformName) {
  85366. // Static uniform
  85367. shaderMaterial.setTexture(uniformName, texture);
  85368. delete unTreatedUniforms[uniformName];
  85369. }
  85370. };
  85371. };
  85372. // Texture (sampler2D)
  85373. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  85374. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  85375. }
  85376. else {
  85377. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  85378. // Static uniform
  85379. delete unTreatedUniforms[unif];
  85380. }
  85381. }
  85382. }
  85383. };
  85384. /**
  85385. * Shader compilation failed
  85386. */
  85387. var onShaderCompileError = function (program, shaderMaterial, onError) {
  85388. return function (effect, error) {
  85389. shaderMaterial.dispose(true);
  85390. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  85391. };
  85392. };
  85393. /**
  85394. * Shader compilation success
  85395. */
  85396. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  85397. return function (_) {
  85398. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  85399. shaderMaterial.onBind = function (mesh) {
  85400. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  85401. };
  85402. };
  85403. };
  85404. /**
  85405. * Returns the appropriate uniform if already handled by babylon
  85406. */
  85407. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  85408. for (var unif in technique.uniforms) {
  85409. var uniform = technique.uniforms[unif];
  85410. var uniformParameter = technique.parameters[uniform];
  85411. if (tokenizer.currentIdentifier === unif) {
  85412. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  85413. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  85414. if (transformIndex !== -1) {
  85415. delete unTreatedUniforms[unif];
  85416. return babylonTransforms[transformIndex];
  85417. }
  85418. }
  85419. }
  85420. }
  85421. return tokenizer.currentIdentifier;
  85422. };
  85423. /**
  85424. * All shaders loaded. Create materials one by one
  85425. */
  85426. var importMaterials = function (gltfRuntime) {
  85427. // Create materials
  85428. for (var mat in gltfRuntime.materials) {
  85429. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  85430. }
  85431. };
  85432. /**
  85433. * Implementation of the base glTF spec
  85434. */
  85435. var GLTFLoaderBase = /** @class */ (function () {
  85436. function GLTFLoaderBase() {
  85437. }
  85438. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  85439. var gltfRuntime = {
  85440. extensions: {},
  85441. accessors: {},
  85442. buffers: {},
  85443. bufferViews: {},
  85444. meshes: {},
  85445. lights: {},
  85446. cameras: {},
  85447. nodes: {},
  85448. images: {},
  85449. textures: {},
  85450. shaders: {},
  85451. programs: {},
  85452. samplers: {},
  85453. techniques: {},
  85454. materials: {},
  85455. animations: {},
  85456. skins: {},
  85457. extensionsUsed: [],
  85458. scenes: {},
  85459. buffersCount: 0,
  85460. shaderscount: 0,
  85461. scene: scene,
  85462. rootUrl: rootUrl,
  85463. loadedBufferCount: 0,
  85464. loadedBufferViews: {},
  85465. loadedShaderCount: 0,
  85466. importOnlyMeshes: false,
  85467. dummyNodes: []
  85468. };
  85469. // Parse
  85470. if (parsedData.extensions) {
  85471. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  85472. }
  85473. if (parsedData.extensionsUsed) {
  85474. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  85475. }
  85476. if (parsedData.buffers) {
  85477. parseBuffers(parsedData.buffers, gltfRuntime);
  85478. }
  85479. if (parsedData.bufferViews) {
  85480. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  85481. }
  85482. if (parsedData.accessors) {
  85483. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  85484. }
  85485. if (parsedData.meshes) {
  85486. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  85487. }
  85488. if (parsedData.lights) {
  85489. parseObject(parsedData.lights, "lights", gltfRuntime);
  85490. }
  85491. if (parsedData.cameras) {
  85492. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  85493. }
  85494. if (parsedData.nodes) {
  85495. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  85496. }
  85497. if (parsedData.images) {
  85498. parseObject(parsedData.images, "images", gltfRuntime);
  85499. }
  85500. if (parsedData.textures) {
  85501. parseObject(parsedData.textures, "textures", gltfRuntime);
  85502. }
  85503. if (parsedData.shaders) {
  85504. parseShaders(parsedData.shaders, gltfRuntime);
  85505. }
  85506. if (parsedData.programs) {
  85507. parseObject(parsedData.programs, "programs", gltfRuntime);
  85508. }
  85509. if (parsedData.samplers) {
  85510. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  85511. }
  85512. if (parsedData.techniques) {
  85513. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  85514. }
  85515. if (parsedData.materials) {
  85516. parseObject(parsedData.materials, "materials", gltfRuntime);
  85517. }
  85518. if (parsedData.animations) {
  85519. parseObject(parsedData.animations, "animations", gltfRuntime);
  85520. }
  85521. if (parsedData.skins) {
  85522. parseObject(parsedData.skins, "skins", gltfRuntime);
  85523. }
  85524. if (parsedData.scenes) {
  85525. gltfRuntime.scenes = parsedData.scenes;
  85526. }
  85527. if (parsedData.scene && parsedData.scenes) {
  85528. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  85529. }
  85530. return gltfRuntime;
  85531. };
  85532. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  85533. var buffer = gltfRuntime.buffers[id];
  85534. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  85535. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  85536. }
  85537. else {
  85538. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  85539. if (request) {
  85540. onError(request.status + " " + request.statusText);
  85541. }
  85542. });
  85543. }
  85544. };
  85545. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  85546. var texture = gltfRuntime.textures[id];
  85547. if (!texture || !texture.source) {
  85548. onError("");
  85549. return;
  85550. }
  85551. if (texture.babylonTexture) {
  85552. onSuccess(null);
  85553. return;
  85554. }
  85555. var source = gltfRuntime.images[texture.source];
  85556. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  85557. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  85558. }
  85559. else {
  85560. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  85561. if (request) {
  85562. onError(request.status + " " + request.statusText);
  85563. }
  85564. });
  85565. }
  85566. };
  85567. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  85568. var texture = gltfRuntime.textures[id];
  85569. if (texture.babylonTexture) {
  85570. onSuccess(texture.babylonTexture);
  85571. return;
  85572. }
  85573. var sampler = gltfRuntime.samplers[texture.sampler];
  85574. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  85575. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  85576. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  85577. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  85578. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  85579. var blob = new Blob([buffer]);
  85580. var blobURL = URL.createObjectURL(blob);
  85581. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  85582. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  85583. if (sampler.wrapS !== undefined) {
  85584. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  85585. }
  85586. if (sampler.wrapT !== undefined) {
  85587. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  85588. }
  85589. newTexture.name = id;
  85590. texture.babylonTexture = newTexture;
  85591. onSuccess(newTexture);
  85592. };
  85593. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  85594. var shader = gltfRuntime.shaders[id];
  85595. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  85596. var shaderString = atob(shader.uri.split(",")[1]);
  85597. onSuccess(shaderString);
  85598. }
  85599. else {
  85600. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  85601. if (request) {
  85602. onError(request.status + " " + request.statusText);
  85603. }
  85604. });
  85605. }
  85606. };
  85607. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  85608. var material = gltfRuntime.materials[id];
  85609. if (!material.technique) {
  85610. if (onError) {
  85611. onError("No technique found.");
  85612. }
  85613. return;
  85614. }
  85615. var technique = gltfRuntime.techniques[material.technique];
  85616. if (!technique) {
  85617. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  85618. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  85619. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  85620. onSuccess(defaultMaterial);
  85621. return;
  85622. }
  85623. var program = gltfRuntime.programs[technique.program];
  85624. var states = technique.states;
  85625. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  85626. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  85627. var newVertexShader = "";
  85628. var newPixelShader = "";
  85629. var vertexTokenizer = new Tokenizer(vertexShader);
  85630. var pixelTokenizer = new Tokenizer(pixelShader);
  85631. var unTreatedUniforms = {};
  85632. var uniforms = [];
  85633. var attributes = [];
  85634. var samplers = [];
  85635. // Fill uniform, sampler2D and attributes
  85636. for (var unif in technique.uniforms) {
  85637. var uniform = technique.uniforms[unif];
  85638. var uniformParameter = technique.parameters[uniform];
  85639. unTreatedUniforms[unif] = uniformParameter;
  85640. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  85641. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  85642. if (transformIndex !== -1) {
  85643. uniforms.push(babylonTransforms[transformIndex]);
  85644. delete unTreatedUniforms[unif];
  85645. }
  85646. else {
  85647. uniforms.push(unif);
  85648. }
  85649. }
  85650. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  85651. samplers.push(unif);
  85652. }
  85653. else {
  85654. uniforms.push(unif);
  85655. }
  85656. }
  85657. for (var attr in technique.attributes) {
  85658. var attribute = technique.attributes[attr];
  85659. var attributeParameter = technique.parameters[attribute];
  85660. if (attributeParameter.semantic) {
  85661. attributes.push(getAttribute(attributeParameter));
  85662. }
  85663. }
  85664. // Configure vertex shader
  85665. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  85666. var tokenType = vertexTokenizer.currentToken;
  85667. if (tokenType !== ETokenType.IDENTIFIER) {
  85668. newVertexShader += vertexTokenizer.currentString;
  85669. continue;
  85670. }
  85671. var foundAttribute = false;
  85672. for (var attr in technique.attributes) {
  85673. var attribute = technique.attributes[attr];
  85674. var attributeParameter = technique.parameters[attribute];
  85675. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  85676. newVertexShader += getAttribute(attributeParameter);
  85677. foundAttribute = true;
  85678. break;
  85679. }
  85680. }
  85681. if (foundAttribute) {
  85682. continue;
  85683. }
  85684. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  85685. }
  85686. // Configure pixel shader
  85687. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  85688. var tokenType = pixelTokenizer.currentToken;
  85689. if (tokenType !== ETokenType.IDENTIFIER) {
  85690. newPixelShader += pixelTokenizer.currentString;
  85691. continue;
  85692. }
  85693. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  85694. }
  85695. // Create shader material
  85696. var shaderPath = {
  85697. vertex: program.vertexShader + id,
  85698. fragment: program.fragmentShader + id
  85699. };
  85700. var options = {
  85701. attributes: attributes,
  85702. uniforms: uniforms,
  85703. samplers: samplers,
  85704. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  85705. };
  85706. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  85707. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  85708. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  85709. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  85710. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  85711. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  85712. if (states && states.functions) {
  85713. var functions = states.functions;
  85714. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  85715. shaderMaterial.backFaceCulling = false;
  85716. }
  85717. var blendFunc = functions.blendFuncSeparate;
  85718. if (blendFunc) {
  85719. 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) {
  85720. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  85721. }
  85722. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85723. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  85724. }
  85725. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85726. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  85727. }
  85728. 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) {
  85729. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  85730. }
  85731. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85732. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  85733. }
  85734. 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) {
  85735. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  85736. }
  85737. }
  85738. }
  85739. };
  85740. return GLTFLoaderBase;
  85741. }());
  85742. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  85743. /**
  85744. * glTF V1 Loader
  85745. */
  85746. var GLTFLoader = /** @class */ (function () {
  85747. function GLTFLoader() {
  85748. // #region Stubs for IGLTFLoader interface
  85749. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  85750. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  85751. this.compileMaterials = false;
  85752. this.useClipPlane = false;
  85753. this.compileShadowGenerators = false;
  85754. this.onDisposeObservable = new BABYLON.Observable();
  85755. this.onMeshLoadedObservable = new BABYLON.Observable();
  85756. this.onTextureLoadedObservable = new BABYLON.Observable();
  85757. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85758. this.onCompleteObservable = new BABYLON.Observable();
  85759. }
  85760. GLTFLoader.RegisterExtension = function (extension) {
  85761. if (GLTFLoader.Extensions[extension.name]) {
  85762. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  85763. return;
  85764. }
  85765. GLTFLoader.Extensions[extension.name] = extension;
  85766. };
  85767. GLTFLoader.prototype.dispose = function () { };
  85768. // #endregion
  85769. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85770. var _this = this;
  85771. scene.useRightHandedSystem = true;
  85772. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  85773. gltfRuntime.importOnlyMeshes = true;
  85774. if (meshesNames === "") {
  85775. gltfRuntime.importMeshesNames = [];
  85776. }
  85777. else if (typeof meshesNames === "string") {
  85778. gltfRuntime.importMeshesNames = [meshesNames];
  85779. }
  85780. else if (meshesNames && !(meshesNames instanceof Array)) {
  85781. gltfRuntime.importMeshesNames = [meshesNames];
  85782. }
  85783. else {
  85784. gltfRuntime.importMeshesNames = [];
  85785. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  85786. }
  85787. // Create nodes
  85788. _this._createNodes(gltfRuntime);
  85789. var meshes = new Array();
  85790. var skeletons = new Array();
  85791. // Fill arrays of meshes and skeletons
  85792. for (var nde in gltfRuntime.nodes) {
  85793. var node = gltfRuntime.nodes[nde];
  85794. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  85795. meshes.push(node.babylonNode);
  85796. }
  85797. }
  85798. for (var skl in gltfRuntime.skins) {
  85799. var skin = gltfRuntime.skins[skl];
  85800. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  85801. skeletons.push(skin.babylonSkeleton);
  85802. }
  85803. }
  85804. // Load buffers, shaders, materials, etc.
  85805. _this._loadBuffersAsync(gltfRuntime, function () {
  85806. _this._loadShadersAsync(gltfRuntime, function () {
  85807. importMaterials(gltfRuntime);
  85808. postLoad(gltfRuntime);
  85809. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  85810. onSuccess(meshes, [], skeletons);
  85811. }
  85812. });
  85813. }, onProgress);
  85814. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  85815. onSuccess(meshes, [], skeletons);
  85816. }
  85817. }, onError);
  85818. return true;
  85819. };
  85820. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85821. var _this = this;
  85822. scene.useRightHandedSystem = true;
  85823. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  85824. // Load runtime extensios
  85825. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  85826. // Create nodes
  85827. _this._createNodes(gltfRuntime);
  85828. // Load buffers, shaders, materials, etc.
  85829. _this._loadBuffersAsync(gltfRuntime, function () {
  85830. _this._loadShadersAsync(gltfRuntime, function () {
  85831. importMaterials(gltfRuntime);
  85832. postLoad(gltfRuntime);
  85833. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  85834. onSuccess();
  85835. }
  85836. });
  85837. });
  85838. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  85839. onSuccess();
  85840. }
  85841. }, onError);
  85842. }, onError);
  85843. };
  85844. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  85845. var hasShaders = false;
  85846. var processShader = function (sha, shader) {
  85847. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  85848. gltfRuntime.loadedShaderCount++;
  85849. if (shaderString) {
  85850. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  85851. }
  85852. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  85853. onload();
  85854. }
  85855. }, function () {
  85856. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  85857. });
  85858. };
  85859. for (var sha in gltfRuntime.shaders) {
  85860. hasShaders = true;
  85861. var shader = gltfRuntime.shaders[sha];
  85862. if (shader) {
  85863. processShader.bind(this, sha, shader)();
  85864. }
  85865. else {
  85866. BABYLON.Tools.Error("No shader named: " + sha);
  85867. }
  85868. }
  85869. if (!hasShaders) {
  85870. onload();
  85871. }
  85872. };
  85873. ;
  85874. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  85875. var hasBuffers = false;
  85876. var processBuffer = function (buf, buffer) {
  85877. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  85878. gltfRuntime.loadedBufferCount++;
  85879. if (bufferView) {
  85880. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  85881. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  85882. }
  85883. gltfRuntime.loadedBufferViews[buf] = bufferView;
  85884. }
  85885. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  85886. onLoad();
  85887. }
  85888. }, function () {
  85889. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  85890. });
  85891. };
  85892. for (var buf in gltfRuntime.buffers) {
  85893. hasBuffers = true;
  85894. var buffer = gltfRuntime.buffers[buf];
  85895. if (buffer) {
  85896. processBuffer.bind(this, buf, buffer)();
  85897. }
  85898. else {
  85899. BABYLON.Tools.Error("No buffer named: " + buf);
  85900. }
  85901. }
  85902. if (!hasBuffers) {
  85903. onLoad();
  85904. }
  85905. };
  85906. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  85907. var currentScene = gltfRuntime.currentScene;
  85908. if (currentScene) {
  85909. // Only one scene even if multiple scenes are defined
  85910. for (var i = 0; i < currentScene.nodes.length; i++) {
  85911. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85912. }
  85913. }
  85914. else {
  85915. // Load all scenes
  85916. for (var thing in gltfRuntime.scenes) {
  85917. currentScene = gltfRuntime.scenes[thing];
  85918. for (var i = 0; i < currentScene.nodes.length; i++) {
  85919. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85920. }
  85921. }
  85922. }
  85923. };
  85924. GLTFLoader.Extensions = {};
  85925. return GLTFLoader;
  85926. }());
  85927. GLTF1.GLTFLoader = GLTFLoader;
  85928. ;
  85929. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  85930. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85931. })(BABYLON || (BABYLON = {}));
  85932. //# sourceMappingURL=babylon.glTFLoader.js.map
  85933. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85934. var BABYLON;
  85935. (function (BABYLON) {
  85936. var GLTF1;
  85937. (function (GLTF1) {
  85938. /**
  85939. * Utils functions for GLTF
  85940. */
  85941. var GLTFUtils = /** @class */ (function () {
  85942. function GLTFUtils() {
  85943. }
  85944. /**
  85945. * Sets the given "parameter" matrix
  85946. * @param scene: the {BABYLON.Scene} object
  85947. * @param source: the source node where to pick the matrix
  85948. * @param parameter: the GLTF technique parameter
  85949. * @param uniformName: the name of the shader's uniform
  85950. * @param shaderMaterial: the shader material
  85951. */
  85952. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  85953. var mat = null;
  85954. if (parameter.semantic === "MODEL") {
  85955. mat = source.getWorldMatrix();
  85956. }
  85957. else if (parameter.semantic === "PROJECTION") {
  85958. mat = scene.getProjectionMatrix();
  85959. }
  85960. else if (parameter.semantic === "VIEW") {
  85961. mat = scene.getViewMatrix();
  85962. }
  85963. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  85964. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  85965. }
  85966. else if (parameter.semantic === "MODELVIEW") {
  85967. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  85968. }
  85969. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  85970. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  85971. }
  85972. else if (parameter.semantic === "MODELINVERSE") {
  85973. mat = source.getWorldMatrix().invert();
  85974. }
  85975. else if (parameter.semantic === "VIEWINVERSE") {
  85976. mat = scene.getViewMatrix().invert();
  85977. }
  85978. else if (parameter.semantic === "PROJECTIONINVERSE") {
  85979. mat = scene.getProjectionMatrix().invert();
  85980. }
  85981. else if (parameter.semantic === "MODELVIEWINVERSE") {
  85982. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  85983. }
  85984. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  85985. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  85986. }
  85987. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  85988. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  85989. }
  85990. else {
  85991. debugger;
  85992. }
  85993. if (mat) {
  85994. switch (parameter.type) {
  85995. case GLTF1.EParameterType.FLOAT_MAT2:
  85996. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  85997. break;
  85998. case GLTF1.EParameterType.FLOAT_MAT3:
  85999. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  86000. break;
  86001. case GLTF1.EParameterType.FLOAT_MAT4:
  86002. shaderMaterial.setMatrix(uniformName, mat);
  86003. break;
  86004. default: break;
  86005. }
  86006. }
  86007. };
  86008. /**
  86009. * Sets the given "parameter" matrix
  86010. * @param shaderMaterial: the shader material
  86011. * @param uniform: the name of the shader's uniform
  86012. * @param value: the value of the uniform
  86013. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  86014. */
  86015. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  86016. switch (type) {
  86017. case GLTF1.EParameterType.FLOAT:
  86018. shaderMaterial.setFloat(uniform, value);
  86019. return true;
  86020. case GLTF1.EParameterType.FLOAT_VEC2:
  86021. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  86022. return true;
  86023. case GLTF1.EParameterType.FLOAT_VEC3:
  86024. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  86025. return true;
  86026. case GLTF1.EParameterType.FLOAT_VEC4:
  86027. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  86028. return true;
  86029. default: return false;
  86030. }
  86031. };
  86032. /**
  86033. * If the uri is a base64 string
  86034. * @param uri: the uri to test
  86035. */
  86036. GLTFUtils.IsBase64 = function (uri) {
  86037. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  86038. };
  86039. /**
  86040. * Decode the base64 uri
  86041. * @param uri: the uri to decode
  86042. */
  86043. GLTFUtils.DecodeBase64 = function (uri) {
  86044. var decodedString = atob(uri.split(",")[1]);
  86045. var bufferLength = decodedString.length;
  86046. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  86047. for (var i = 0; i < bufferLength; i++) {
  86048. bufferView[i] = decodedString.charCodeAt(i);
  86049. }
  86050. return bufferView.buffer;
  86051. };
  86052. /**
  86053. * Returns the wrap mode of the texture
  86054. * @param mode: the mode value
  86055. */
  86056. GLTFUtils.GetWrapMode = function (mode) {
  86057. switch (mode) {
  86058. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  86059. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  86060. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  86061. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  86062. }
  86063. };
  86064. /**
  86065. * Returns the byte stride giving an accessor
  86066. * @param accessor: the GLTF accessor objet
  86067. */
  86068. GLTFUtils.GetByteStrideFromType = function (accessor) {
  86069. // Needs this function since "byteStride" isn't requiered in glTF format
  86070. var type = accessor.type;
  86071. switch (type) {
  86072. case "VEC2": return 2;
  86073. case "VEC3": return 3;
  86074. case "VEC4": return 4;
  86075. case "MAT2": return 4;
  86076. case "MAT3": return 9;
  86077. case "MAT4": return 16;
  86078. default: return 1;
  86079. }
  86080. };
  86081. /**
  86082. * Returns the texture filter mode giving a mode value
  86083. * @param mode: the filter mode value
  86084. */
  86085. GLTFUtils.GetTextureFilterMode = function (mode) {
  86086. switch (mode) {
  86087. case GLTF1.ETextureFilterType.LINEAR:
  86088. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  86089. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  86090. case GLTF1.ETextureFilterType.NEAREST:
  86091. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  86092. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  86093. }
  86094. };
  86095. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  86096. var byteOffset = bufferView.byteOffset + byteOffset;
  86097. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  86098. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  86099. throw new Error("Buffer access is out of range");
  86100. }
  86101. var buffer = loadedBufferView.buffer;
  86102. byteOffset += loadedBufferView.byteOffset;
  86103. switch (componentType) {
  86104. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  86105. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  86106. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  86107. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  86108. default: return new Float32Array(buffer, byteOffset, byteLength);
  86109. }
  86110. };
  86111. /**
  86112. * Returns a buffer from its accessor
  86113. * @param gltfRuntime: the GLTF runtime
  86114. * @param accessor: the GLTF accessor
  86115. */
  86116. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  86117. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  86118. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  86119. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  86120. };
  86121. /**
  86122. * Decodes a buffer view into a string
  86123. * @param view: the buffer view
  86124. */
  86125. GLTFUtils.DecodeBufferToText = function (view) {
  86126. var result = "";
  86127. var length = view.byteLength;
  86128. for (var i = 0; i < length; ++i) {
  86129. result += String.fromCharCode(view[i]);
  86130. }
  86131. return result;
  86132. };
  86133. /**
  86134. * Returns the default material of gltf. Related to
  86135. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  86136. * @param scene: the Babylon.js scene
  86137. */
  86138. GLTFUtils.GetDefaultMaterial = function (scene) {
  86139. if (!GLTFUtils._DefaultMaterial) {
  86140. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  86141. "precision highp float;",
  86142. "",
  86143. "uniform mat4 worldView;",
  86144. "uniform mat4 projection;",
  86145. "",
  86146. "attribute vec3 position;",
  86147. "",
  86148. "void main(void)",
  86149. "{",
  86150. " gl_Position = projection * worldView * vec4(position, 1.0);",
  86151. "}"
  86152. ].join("\n");
  86153. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  86154. "precision highp float;",
  86155. "",
  86156. "uniform vec4 u_emission;",
  86157. "",
  86158. "void main(void)",
  86159. "{",
  86160. " gl_FragColor = u_emission;",
  86161. "}"
  86162. ].join("\n");
  86163. var shaderPath = {
  86164. vertex: "GLTFDefaultMaterial",
  86165. fragment: "GLTFDefaultMaterial"
  86166. };
  86167. var options = {
  86168. attributes: ["position"],
  86169. uniforms: ["worldView", "projection", "u_emission"],
  86170. samplers: new Array(),
  86171. needAlphaBlending: false
  86172. };
  86173. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  86174. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  86175. }
  86176. return GLTFUtils._DefaultMaterial;
  86177. };
  86178. // The GLTF default material
  86179. GLTFUtils._DefaultMaterial = null;
  86180. return GLTFUtils;
  86181. }());
  86182. GLTF1.GLTFUtils = GLTFUtils;
  86183. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86184. })(BABYLON || (BABYLON = {}));
  86185. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  86186. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86187. var BABYLON;
  86188. (function (BABYLON) {
  86189. var GLTF1;
  86190. (function (GLTF1) {
  86191. var GLTFLoaderExtension = /** @class */ (function () {
  86192. function GLTFLoaderExtension(name) {
  86193. this._name = name;
  86194. }
  86195. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  86196. get: function () {
  86197. return this._name;
  86198. },
  86199. enumerable: true,
  86200. configurable: true
  86201. });
  86202. /**
  86203. * Defines an override for loading the runtime
  86204. * Return true to stop further extensions from loading the runtime
  86205. */
  86206. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86207. return false;
  86208. };
  86209. /**
  86210. * Defines an onverride for creating gltf runtime
  86211. * Return true to stop further extensions from creating the runtime
  86212. */
  86213. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86214. return false;
  86215. };
  86216. /**
  86217. * Defines an override for loading buffers
  86218. * Return true to stop further extensions from loading this buffer
  86219. */
  86220. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86221. return false;
  86222. };
  86223. /**
  86224. * Defines an override for loading texture buffers
  86225. * Return true to stop further extensions from loading this texture data
  86226. */
  86227. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86228. return false;
  86229. };
  86230. /**
  86231. * Defines an override for creating textures
  86232. * Return true to stop further extensions from loading this texture
  86233. */
  86234. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86235. return false;
  86236. };
  86237. /**
  86238. * Defines an override for loading shader strings
  86239. * Return true to stop further extensions from loading this shader data
  86240. */
  86241. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86242. return false;
  86243. };
  86244. /**
  86245. * Defines an override for loading materials
  86246. * Return true to stop further extensions from loading this material
  86247. */
  86248. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86249. return false;
  86250. };
  86251. // ---------
  86252. // Utilities
  86253. // ---------
  86254. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86255. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86256. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  86257. }, function () {
  86258. setTimeout(function () {
  86259. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  86260. });
  86261. });
  86262. };
  86263. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86264. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86265. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  86266. }, function () {
  86267. setTimeout(function () {
  86268. onSuccess();
  86269. });
  86270. });
  86271. };
  86272. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  86273. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86274. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  86275. }, function () {
  86276. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  86277. });
  86278. };
  86279. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  86280. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  86281. };
  86282. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86283. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86284. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  86285. }, function () {
  86286. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  86287. });
  86288. };
  86289. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86290. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86291. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  86292. }, function () {
  86293. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  86294. });
  86295. };
  86296. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86297. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86298. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  86299. }, function () {
  86300. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  86301. });
  86302. };
  86303. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  86304. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  86305. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  86306. }, function () {
  86307. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  86308. });
  86309. };
  86310. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  86311. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  86312. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  86313. if (func(loaderExtension)) {
  86314. return;
  86315. }
  86316. }
  86317. defaultFunc();
  86318. };
  86319. return GLTFLoaderExtension;
  86320. }());
  86321. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  86322. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86323. })(BABYLON || (BABYLON = {}));
  86324. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  86325. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86326. var BABYLON;
  86327. (function (BABYLON) {
  86328. var GLTF1;
  86329. (function (GLTF1) {
  86330. var BinaryExtensionBufferName = "binary_glTF";
  86331. ;
  86332. ;
  86333. var GLTFBinaryExtension = /** @class */ (function (_super) {
  86334. __extends(GLTFBinaryExtension, _super);
  86335. function GLTFBinaryExtension() {
  86336. return _super.call(this, "KHR_binary_glTF") || this;
  86337. }
  86338. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  86339. var extensionsUsed = data.json.extensionsUsed;
  86340. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  86341. return false;
  86342. }
  86343. this._bin = data.bin;
  86344. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  86345. return true;
  86346. };
  86347. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86348. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  86349. return false;
  86350. }
  86351. if (id !== BinaryExtensionBufferName) {
  86352. return false;
  86353. }
  86354. onSuccess(this._bin);
  86355. return true;
  86356. };
  86357. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86358. var texture = gltfRuntime.textures[id];
  86359. var source = gltfRuntime.images[texture.source];
  86360. if (!source.extensions || !(this.name in source.extensions)) {
  86361. return false;
  86362. }
  86363. var sourceExt = source.extensions[this.name];
  86364. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  86365. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86366. onSuccess(buffer);
  86367. return true;
  86368. };
  86369. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86370. var shader = gltfRuntime.shaders[id];
  86371. if (!shader.extensions || !(this.name in shader.extensions)) {
  86372. return false;
  86373. }
  86374. var binaryExtensionShader = shader.extensions[this.name];
  86375. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  86376. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86377. setTimeout(function () {
  86378. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  86379. onSuccess(shaderString);
  86380. });
  86381. return true;
  86382. };
  86383. return GLTFBinaryExtension;
  86384. }(GLTF1.GLTFLoaderExtension));
  86385. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  86386. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  86387. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86388. })(BABYLON || (BABYLON = {}));
  86389. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  86390. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86391. var BABYLON;
  86392. (function (BABYLON) {
  86393. var GLTF1;
  86394. (function (GLTF1) {
  86395. ;
  86396. ;
  86397. ;
  86398. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  86399. __extends(GLTFMaterialsCommonExtension, _super);
  86400. function GLTFMaterialsCommonExtension() {
  86401. return _super.call(this, "KHR_materials_common") || this;
  86402. }
  86403. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86404. if (!gltfRuntime.extensions)
  86405. return false;
  86406. var extension = gltfRuntime.extensions[this.name];
  86407. if (!extension)
  86408. return false;
  86409. // Create lights
  86410. var lights = extension.lights;
  86411. if (lights) {
  86412. for (var thing in lights) {
  86413. var light = lights[thing];
  86414. switch (light.type) {
  86415. case "ambient":
  86416. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  86417. var ambient = light.ambient;
  86418. if (ambient) {
  86419. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  86420. }
  86421. break;
  86422. case "point":
  86423. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  86424. var point = light.point;
  86425. if (point) {
  86426. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  86427. }
  86428. break;
  86429. case "directional":
  86430. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  86431. var directional = light.directional;
  86432. if (directional) {
  86433. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  86434. }
  86435. break;
  86436. case "spot":
  86437. var spot = light.spot;
  86438. if (spot) {
  86439. 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);
  86440. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  86441. }
  86442. break;
  86443. default:
  86444. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  86445. break;
  86446. }
  86447. }
  86448. }
  86449. return false;
  86450. };
  86451. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86452. var material = gltfRuntime.materials[id];
  86453. if (!material || !material.extensions)
  86454. return false;
  86455. var extension = material.extensions[this.name];
  86456. if (!extension)
  86457. return false;
  86458. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86459. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86460. if (extension.technique === "CONSTANT") {
  86461. standardMaterial.disableLighting = true;
  86462. }
  86463. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  86464. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  86465. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  86466. // Ambient
  86467. if (typeof extension.values.ambient === "string") {
  86468. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  86469. }
  86470. else {
  86471. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  86472. }
  86473. // Diffuse
  86474. if (typeof extension.values.diffuse === "string") {
  86475. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  86476. }
  86477. else {
  86478. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  86479. }
  86480. // Emission
  86481. if (typeof extension.values.emission === "string") {
  86482. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  86483. }
  86484. else {
  86485. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  86486. }
  86487. // Specular
  86488. if (typeof extension.values.specular === "string") {
  86489. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  86490. }
  86491. else {
  86492. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  86493. }
  86494. return true;
  86495. };
  86496. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  86497. // Create buffer from texture url
  86498. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  86499. // Create texture from buffer
  86500. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  86501. }, onError);
  86502. };
  86503. return GLTFMaterialsCommonExtension;
  86504. }(GLTF1.GLTFLoaderExtension));
  86505. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  86506. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  86507. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86508. })(BABYLON || (BABYLON = {}));
  86509. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  86510. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86511. var BABYLON;
  86512. (function (BABYLON) {
  86513. var GLTF2;
  86514. (function (GLTF2) {
  86515. /**
  86516. * Enums
  86517. */
  86518. var EComponentType;
  86519. (function (EComponentType) {
  86520. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  86521. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86522. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  86523. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86524. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  86525. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  86526. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  86527. var EMeshPrimitiveMode;
  86528. (function (EMeshPrimitiveMode) {
  86529. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  86530. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  86531. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  86532. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  86533. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  86534. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  86535. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  86536. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  86537. var ETextureMagFilter;
  86538. (function (ETextureMagFilter) {
  86539. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  86540. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  86541. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  86542. var ETextureMinFilter;
  86543. (function (ETextureMinFilter) {
  86544. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  86545. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  86546. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  86547. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  86548. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  86549. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  86550. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  86551. var ETextureWrapMode;
  86552. (function (ETextureWrapMode) {
  86553. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  86554. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  86555. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  86556. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  86557. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86558. })(BABYLON || (BABYLON = {}));
  86559. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  86560. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86561. var BABYLON;
  86562. (function (BABYLON) {
  86563. var GLTF2;
  86564. (function (GLTF2) {
  86565. var GLTFLoaderTracker = /** @class */ (function () {
  86566. function GLTFLoaderTracker(onComplete) {
  86567. this._pendingCount = 0;
  86568. this._callback = onComplete;
  86569. }
  86570. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  86571. this._pendingCount++;
  86572. };
  86573. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  86574. if (--this._pendingCount === 0) {
  86575. this._callback();
  86576. }
  86577. };
  86578. return GLTFLoaderTracker;
  86579. }());
  86580. var GLTFLoader = /** @class */ (function () {
  86581. function GLTFLoader() {
  86582. this._disposed = false;
  86583. this._defaultSampler = {};
  86584. this._renderReady = false;
  86585. this._requests = new Array();
  86586. this._renderReadyObservable = new BABYLON.Observable();
  86587. // Count of pending work that needs to complete before the asset is rendered.
  86588. this._renderPendingCount = 0;
  86589. // Count of pending work that needs to complete before the loader is disposed.
  86590. this._loaderPendingCount = 0;
  86591. this._loaderTrackers = new Array();
  86592. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  86593. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  86594. this.compileMaterials = false;
  86595. this.useClipPlane = false;
  86596. this.compileShadowGenerators = false;
  86597. this.onDisposeObservable = new BABYLON.Observable();
  86598. this.onMeshLoadedObservable = new BABYLON.Observable();
  86599. this.onTextureLoadedObservable = new BABYLON.Observable();
  86600. this.onMaterialLoadedObservable = new BABYLON.Observable();
  86601. this.onCompleteObservable = new BABYLON.Observable();
  86602. }
  86603. GLTFLoader.RegisterExtension = function (extension) {
  86604. if (GLTFLoader.Extensions[extension.name]) {
  86605. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  86606. return;
  86607. }
  86608. GLTFLoader.Extensions[extension.name] = extension;
  86609. // Keep the order of registration so that extensions registered first are called first.
  86610. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  86611. };
  86612. GLTFLoader.prototype.dispose = function () {
  86613. if (this._disposed) {
  86614. return;
  86615. }
  86616. this._disposed = true;
  86617. this._abortRequests();
  86618. this._releaseResources();
  86619. this.onDisposeObservable.notifyObservers(this);
  86620. };
  86621. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  86622. var _this = this;
  86623. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  86624. if (onSuccess) {
  86625. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  86626. }
  86627. }, onProgress, onError);
  86628. };
  86629. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  86630. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  86631. };
  86632. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  86633. var _this = this;
  86634. this._babylonScene = scene;
  86635. this._rootUrl = rootUrl;
  86636. this._successCallback = onSuccess;
  86637. this._progressCallback = onProgress;
  86638. this._errorCallback = onError;
  86639. this._tryCatchOnError(function () {
  86640. _this._loadData(data);
  86641. _this._addPendingData(_this);
  86642. _this._loadDefaultScene(nodeNames);
  86643. _this._loadAnimations();
  86644. _this._removePendingData(_this);
  86645. });
  86646. };
  86647. GLTFLoader.prototype._onProgress = function () {
  86648. if (!this._progressCallback) {
  86649. return;
  86650. }
  86651. var lengthComputable = true;
  86652. var loaded = 0;
  86653. var total = 0;
  86654. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  86655. var request = _a[_i];
  86656. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  86657. return;
  86658. }
  86659. lengthComputable = lengthComputable && request._lengthComputable;
  86660. loaded += request._loaded;
  86661. total += request._total;
  86662. }
  86663. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  86664. };
  86665. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  86666. if (this._renderReady) {
  86667. func();
  86668. }
  86669. else {
  86670. this._renderReadyObservable.add(func);
  86671. }
  86672. };
  86673. GLTFLoader.prototype._onRenderReady = function () {
  86674. this._rootNode.babylonMesh.setEnabled(true);
  86675. this._startAnimations();
  86676. if (this._successCallback) {
  86677. this._successCallback();
  86678. }
  86679. this._renderReadyObservable.notifyObservers(this);
  86680. };
  86681. GLTFLoader.prototype._onComplete = function () {
  86682. this._abortRequests();
  86683. this._releaseResources();
  86684. this.onCompleteObservable.notifyObservers(this);
  86685. };
  86686. GLTFLoader.prototype._loadData = function (data) {
  86687. this._gltf = data.json;
  86688. // Assign the index of each object for convinience.
  86689. GLTFLoader._AssignIndices(this._gltf.accessors);
  86690. GLTFLoader._AssignIndices(this._gltf.animations);
  86691. GLTFLoader._AssignIndices(this._gltf.buffers);
  86692. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  86693. GLTFLoader._AssignIndices(this._gltf.images);
  86694. GLTFLoader._AssignIndices(this._gltf.materials);
  86695. GLTFLoader._AssignIndices(this._gltf.meshes);
  86696. GLTFLoader._AssignIndices(this._gltf.nodes);
  86697. GLTFLoader._AssignIndices(this._gltf.samplers);
  86698. GLTFLoader._AssignIndices(this._gltf.scenes);
  86699. GLTFLoader._AssignIndices(this._gltf.skins);
  86700. GLTFLoader._AssignIndices(this._gltf.textures);
  86701. if (data.bin) {
  86702. var buffers = this._gltf.buffers;
  86703. if (buffers && buffers[0] && !buffers[0].uri) {
  86704. var binaryBuffer = buffers[0];
  86705. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  86706. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  86707. }
  86708. binaryBuffer.loadedData = data.bin;
  86709. }
  86710. else {
  86711. BABYLON.Tools.Warn("Unexpected BIN chunk");
  86712. }
  86713. }
  86714. };
  86715. GLTFLoader.prototype._getMeshes = function () {
  86716. var meshes = new Array();
  86717. // Root mesh is always first.
  86718. meshes.push(this._rootNode.babylonMesh);
  86719. var nodes = this._gltf.nodes;
  86720. if (nodes) {
  86721. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  86722. var node = nodes_1[_i];
  86723. if (node.babylonMesh) {
  86724. meshes.push(node.babylonMesh);
  86725. }
  86726. }
  86727. }
  86728. return meshes;
  86729. };
  86730. GLTFLoader.prototype._getSkeletons = function () {
  86731. var skeletons = new Array();
  86732. var skins = this._gltf.skins;
  86733. if (skins) {
  86734. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  86735. var skin = skins_1[_i];
  86736. if (skin.babylonSkeleton) {
  86737. skeletons.push(skin.babylonSkeleton);
  86738. }
  86739. }
  86740. }
  86741. return skeletons;
  86742. };
  86743. GLTFLoader.prototype._startAnimations = function () {
  86744. var animations = this._gltf.animations;
  86745. if (!animations) {
  86746. return;
  86747. }
  86748. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  86749. var animation = animations_1[_i];
  86750. animation.babylonAnimationGroup.normalize();
  86751. }
  86752. switch (this.animationStartMode) {
  86753. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  86754. // do nothing
  86755. break;
  86756. }
  86757. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  86758. var animation = animations[0];
  86759. animation.babylonAnimationGroup.start(true);
  86760. break;
  86761. }
  86762. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  86763. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  86764. var animation = animations_2[_a];
  86765. animation.babylonAnimationGroup.start(true);
  86766. }
  86767. break;
  86768. }
  86769. default: {
  86770. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  86771. return;
  86772. }
  86773. }
  86774. };
  86775. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  86776. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  86777. if (!scene) {
  86778. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  86779. }
  86780. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  86781. };
  86782. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  86783. var _this = this;
  86784. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  86785. switch (this.coordinateSystemMode) {
  86786. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  86787. if (!this._babylonScene.useRightHandedSystem) {
  86788. this._rootNode.rotation = [0, 1, 0, 0];
  86789. this._rootNode.scale = [1, 1, -1];
  86790. this._loadTransform(this._rootNode);
  86791. }
  86792. break;
  86793. }
  86794. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  86795. this._babylonScene.useRightHandedSystem = true;
  86796. break;
  86797. }
  86798. default: {
  86799. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  86800. return;
  86801. }
  86802. }
  86803. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  86804. var nodeIndices = scene.nodes;
  86805. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  86806. node.parent = parentNode;
  86807. return true;
  86808. }, this._rootNode);
  86809. if (nodeNames) {
  86810. if (!(nodeNames instanceof Array)) {
  86811. nodeNames = [nodeNames];
  86812. }
  86813. var filteredNodeIndices_1 = new Array();
  86814. this._traverseNodes(context, nodeIndices, function (node) {
  86815. if (nodeNames.indexOf(node.name) !== -1) {
  86816. filteredNodeIndices_1.push(node.index);
  86817. node.parent = _this._rootNode;
  86818. return false;
  86819. }
  86820. return true;
  86821. }, this._rootNode);
  86822. nodeIndices = filteredNodeIndices_1;
  86823. }
  86824. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  86825. var index = nodeIndices_1[_i];
  86826. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86827. if (!node) {
  86828. throw new Error(context + ": Failed to find node " + index);
  86829. }
  86830. this._loadNode("#/nodes/" + index, node);
  86831. }
  86832. // Disable the root mesh until the asset is ready to render.
  86833. this._rootNode.babylonMesh.setEnabled(false);
  86834. };
  86835. GLTFLoader.prototype._loadNode = function (context, node) {
  86836. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  86837. return;
  86838. }
  86839. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  86840. this._loadTransform(node);
  86841. if (node.mesh != null) {
  86842. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  86843. if (!mesh) {
  86844. throw new Error(context + ": Failed to find mesh " + node.mesh);
  86845. }
  86846. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  86847. }
  86848. node.babylonMesh.parent = node.parent.babylonMesh;
  86849. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  86850. node.babylonAnimationTargets.push(node.babylonMesh);
  86851. if (node.skin != null) {
  86852. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  86853. if (!skin_1) {
  86854. throw new Error(context + ": Failed to find skin " + node.skin);
  86855. }
  86856. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  86857. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  86858. node.babylonMesh._refreshBoundingInfo(true);
  86859. });
  86860. node.babylonMesh.parent = this._rootNode.babylonMesh;
  86861. node.babylonMesh.position = BABYLON.Vector3.Zero();
  86862. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86863. node.babylonMesh.scaling = BABYLON.Vector3.One();
  86864. }
  86865. if (node.camera != null) {
  86866. // TODO: handle cameras
  86867. }
  86868. if (node.children) {
  86869. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  86870. var index = _a[_i];
  86871. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86872. if (!childNode) {
  86873. throw new Error(context + ": Failed to find child node " + index);
  86874. }
  86875. this._loadNode("#/nodes/" + index, childNode);
  86876. }
  86877. }
  86878. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  86879. };
  86880. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  86881. var _this = this;
  86882. var primitives = mesh.primitives;
  86883. if (!primitives || primitives.length === 0) {
  86884. throw new Error(context + ": Primitives are missing");
  86885. }
  86886. this._createMorphTargets(context, node, mesh);
  86887. this._loadAllVertexDataAsync(context, mesh, function () {
  86888. _this._loadMorphTargets(context, node, mesh);
  86889. var vertexData = new BABYLON.VertexData();
  86890. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  86891. var primitive = primitives_1[_i];
  86892. vertexData.merge(primitive.vertexData);
  86893. }
  86894. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  86895. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  86896. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  86897. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  86898. node.babylonMesh.subMeshes = [];
  86899. var verticesStart = 0;
  86900. var indicesStart = 0;
  86901. for (var index = 0; index < primitives.length; index++) {
  86902. var vertexData_1 = primitives[index].vertexData;
  86903. var verticesCount = vertexData_1.positions.length;
  86904. var indicesCount = vertexData_1.indices.length;
  86905. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  86906. verticesStart += verticesCount;
  86907. indicesStart += indicesCount;
  86908. }
  86909. ;
  86910. });
  86911. if (primitives.length === 1) {
  86912. var primitive = primitives[0];
  86913. if (primitive.material == null) {
  86914. node.babylonMesh.material = this._getDefaultMaterial();
  86915. }
  86916. else {
  86917. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  86918. if (!material) {
  86919. throw new Error(context + ": Failed to find material " + primitive.material);
  86920. }
  86921. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  86922. if (isNew) {
  86923. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  86924. }
  86925. node.babylonMesh.material = babylonMaterial;
  86926. });
  86927. }
  86928. }
  86929. else {
  86930. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  86931. node.babylonMesh.material = multiMaterial;
  86932. var subMaterials_1 = multiMaterial.subMaterials;
  86933. var _loop_1 = function (index) {
  86934. var primitive = primitives[index];
  86935. if (primitive.material == null) {
  86936. subMaterials_1[index] = this_1._getDefaultMaterial();
  86937. }
  86938. else {
  86939. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  86940. if (!material) {
  86941. throw new Error(context + ": Failed to find material " + primitive.material);
  86942. }
  86943. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  86944. if (isNew) {
  86945. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  86946. }
  86947. subMaterials_1[index] = babylonMaterial;
  86948. });
  86949. }
  86950. };
  86951. var this_1 = this;
  86952. for (var index = 0; index < primitives.length; index++) {
  86953. _loop_1(index);
  86954. }
  86955. ;
  86956. }
  86957. };
  86958. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  86959. var primitives = mesh.primitives;
  86960. var numRemainingPrimitives = primitives.length;
  86961. var _loop_2 = function (index) {
  86962. var primitive = primitives[index];
  86963. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  86964. primitive.vertexData = vertexData;
  86965. if (--numRemainingPrimitives === 0) {
  86966. onSuccess();
  86967. }
  86968. });
  86969. };
  86970. var this_2 = this;
  86971. for (var index = 0; index < primitives.length; index++) {
  86972. _loop_2(index);
  86973. }
  86974. };
  86975. /**
  86976. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  86977. * @param {ArrayBufferView} data
  86978. * @param {IGLTFAccessor} accessor
  86979. */
  86980. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  86981. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  86982. return data;
  86983. }
  86984. var buffer = data;
  86985. var factor = 1;
  86986. switch (accessor.componentType) {
  86987. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  86988. factor = 1 / 255;
  86989. break;
  86990. }
  86991. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  86992. factor = 1 / 65535;
  86993. break;
  86994. }
  86995. default: {
  86996. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  86997. }
  86998. }
  86999. var result = new Float32Array(accessor.count * 2);
  87000. for (var i = 0; i < result.length; ++i) {
  87001. result[i] = buffer[i] * factor;
  87002. }
  87003. return result;
  87004. };
  87005. /**
  87006. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  87007. * @param {ArrayBufferView} data
  87008. * @param {IGLTFAccessor} accessor
  87009. */
  87010. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  87011. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  87012. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  87013. return data;
  87014. }
  87015. var buffer = data;
  87016. var factor = 1;
  87017. switch (accessor.componentType) {
  87018. case GLTF2.EComponentType.FLOAT: {
  87019. factor = 1;
  87020. break;
  87021. }
  87022. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  87023. factor = 1 / 255;
  87024. break;
  87025. }
  87026. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  87027. factor = 1 / 65535;
  87028. break;
  87029. }
  87030. default: {
  87031. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  87032. }
  87033. }
  87034. var result = new Float32Array(accessor.count * 4);
  87035. if (colorComponentCount === 4) {
  87036. for (var i = 0; i < result.length; ++i) {
  87037. result[i] = buffer[i] * factor;
  87038. }
  87039. }
  87040. else {
  87041. var offset = 0;
  87042. for (var i = 0; i < result.length; ++i) {
  87043. if ((i + 1) % 4 === 0) {
  87044. result[i] = 1;
  87045. }
  87046. else {
  87047. result[i] = buffer[offset++] * factor;
  87048. }
  87049. }
  87050. }
  87051. return result;
  87052. };
  87053. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  87054. var _this = this;
  87055. var attributes = primitive.attributes;
  87056. if (!attributes) {
  87057. throw new Error(context + ": Attributes are missing");
  87058. }
  87059. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  87060. // TODO: handle other primitive modes
  87061. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  87062. }
  87063. var vertexData = new BABYLON.VertexData();
  87064. var numRemainingAttributes = Object.keys(attributes).length;
  87065. var _loop_3 = function (attribute) {
  87066. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  87067. if (!accessor) {
  87068. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  87069. }
  87070. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87071. switch (attribute) {
  87072. case "POSITION": {
  87073. vertexData.positions = data;
  87074. break;
  87075. }
  87076. case "NORMAL": {
  87077. vertexData.normals = data;
  87078. break;
  87079. }
  87080. case "TANGENT": {
  87081. vertexData.tangents = data;
  87082. break;
  87083. }
  87084. case "TEXCOORD_0": {
  87085. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  87086. break;
  87087. }
  87088. case "TEXCOORD_1": {
  87089. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  87090. break;
  87091. }
  87092. case "JOINTS_0": {
  87093. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  87094. break;
  87095. }
  87096. case "WEIGHTS_0": {
  87097. //TODO: need to add support for normalized weights.
  87098. vertexData.matricesWeights = data;
  87099. break;
  87100. }
  87101. case "COLOR_0": {
  87102. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  87103. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  87104. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  87105. mesh.hasVertexAlpha = hasVertexAlpha;
  87106. }
  87107. break;
  87108. }
  87109. default: {
  87110. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  87111. break;
  87112. }
  87113. }
  87114. if (--numRemainingAttributes === 0) {
  87115. if (primitive.indices == null) {
  87116. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  87117. for (var i = 0; i < vertexData.indices.length; i++) {
  87118. vertexData.indices[i] = i;
  87119. }
  87120. onSuccess(vertexData);
  87121. }
  87122. else {
  87123. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  87124. if (!indicesAccessor) {
  87125. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  87126. }
  87127. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  87128. vertexData.indices = data;
  87129. onSuccess(vertexData);
  87130. });
  87131. }
  87132. }
  87133. });
  87134. };
  87135. var this_3 = this;
  87136. for (var attribute in attributes) {
  87137. _loop_3(attribute);
  87138. }
  87139. };
  87140. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  87141. var primitives = mesh.primitives;
  87142. var targets = primitives[0].targets;
  87143. if (!targets) {
  87144. return;
  87145. }
  87146. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  87147. var primitive = primitives_2[_i];
  87148. if (!primitive.targets || primitive.targets.length != targets.length) {
  87149. throw new Error(context + ": All primitives are required to list the same number of targets");
  87150. }
  87151. }
  87152. var morphTargetManager = new BABYLON.MorphTargetManager();
  87153. node.babylonMesh.morphTargetManager = morphTargetManager;
  87154. for (var index = 0; index < targets.length; index++) {
  87155. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  87156. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  87157. }
  87158. };
  87159. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  87160. var morphTargetManager = node.babylonMesh.morphTargetManager;
  87161. if (!morphTargetManager) {
  87162. return;
  87163. }
  87164. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  87165. var numTargets = morphTargetManager.numTargets;
  87166. for (var index = 0; index < numTargets; index++) {
  87167. var vertexData = new BABYLON.VertexData();
  87168. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  87169. var primitive = _a[_i];
  87170. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  87171. }
  87172. if (!vertexData.positions) {
  87173. throw new Error(context + ": Positions are missing");
  87174. }
  87175. var target = morphTargetManager.getTarget(index);
  87176. target.setPositions(vertexData.positions);
  87177. target.setNormals(vertexData.normals);
  87178. target.setTangents(vertexData.tangents);
  87179. }
  87180. });
  87181. };
  87182. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  87183. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  87184. var _loop_4 = function (primitive) {
  87185. var targets = primitive.targets;
  87186. primitive.targetsVertexData = new Array(targets.length);
  87187. var _loop_5 = function (index) {
  87188. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  87189. primitive.targetsVertexData[index] = vertexData;
  87190. if (--numRemainingTargets === 0) {
  87191. onSuccess();
  87192. }
  87193. });
  87194. };
  87195. for (var index = 0; index < targets.length; index++) {
  87196. _loop_5(index);
  87197. }
  87198. };
  87199. var this_4 = this;
  87200. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  87201. var primitive = _a[_i];
  87202. _loop_4(primitive);
  87203. }
  87204. };
  87205. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  87206. var targetVertexData = new BABYLON.VertexData();
  87207. var numRemainingAttributes = Object.keys(attributes).length;
  87208. var _loop_6 = function (attribute) {
  87209. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  87210. if (!accessor) {
  87211. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  87212. }
  87213. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87214. // glTF stores morph target information as deltas while babylon.js expects the final data.
  87215. // As a result we have to add the original data to the delta to calculate the final data.
  87216. var values = data;
  87217. switch (attribute) {
  87218. case "POSITION": {
  87219. for (var i = 0; i < values.length; i++) {
  87220. values[i] += vertexData.positions[i];
  87221. }
  87222. targetVertexData.positions = values;
  87223. break;
  87224. }
  87225. case "NORMAL": {
  87226. for (var i = 0; i < values.length; i++) {
  87227. values[i] += vertexData.normals[i];
  87228. }
  87229. targetVertexData.normals = values;
  87230. break;
  87231. }
  87232. case "TANGENT": {
  87233. // Tangent data for morph targets is stored as xyz delta.
  87234. // The vertexData.tangent is stored as xyzw.
  87235. // So we need to skip every fourth vertexData.tangent.
  87236. for (var i = 0, j = 0; i < values.length; i++, j++) {
  87237. values[i] += vertexData.tangents[j];
  87238. if ((i + 1) % 3 == 0) {
  87239. j++;
  87240. }
  87241. }
  87242. targetVertexData.tangents = values;
  87243. break;
  87244. }
  87245. default: {
  87246. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  87247. break;
  87248. }
  87249. }
  87250. if (--numRemainingAttributes === 0) {
  87251. onSuccess(targetVertexData);
  87252. }
  87253. });
  87254. };
  87255. var this_5 = this;
  87256. for (var attribute in attributes) {
  87257. _loop_6(attribute);
  87258. }
  87259. };
  87260. GLTFLoader.prototype._loadTransform = function (node) {
  87261. var position = BABYLON.Vector3.Zero();
  87262. var rotation = BABYLON.Quaternion.Identity();
  87263. var scaling = BABYLON.Vector3.One();
  87264. if (node.matrix) {
  87265. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  87266. matrix.decompose(scaling, rotation, position);
  87267. }
  87268. else {
  87269. if (node.translation)
  87270. position = BABYLON.Vector3.FromArray(node.translation);
  87271. if (node.rotation)
  87272. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  87273. if (node.scale)
  87274. scaling = BABYLON.Vector3.FromArray(node.scale);
  87275. }
  87276. node.babylonMesh.position = position;
  87277. node.babylonMesh.rotationQuaternion = rotation;
  87278. node.babylonMesh.scaling = scaling;
  87279. };
  87280. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  87281. var _this = this;
  87282. if (skin.babylonSkeleton) {
  87283. onSuccess();
  87284. return;
  87285. }
  87286. var skeletonId = "skeleton" + skin.index;
  87287. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  87288. if (skin.inverseBindMatrices == null) {
  87289. this._loadBones(context, skin, null);
  87290. onSuccess();
  87291. }
  87292. else {
  87293. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  87294. if (!accessor) {
  87295. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  87296. }
  87297. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  87298. _this._loadBones(context, skin, data);
  87299. onSuccess();
  87300. });
  87301. }
  87302. };
  87303. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  87304. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  87305. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  87306. node.babylonAnimationTargets.push(babylonBone);
  87307. return babylonBone;
  87308. };
  87309. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  87310. var babylonBones = {};
  87311. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  87312. var index = _a[_i];
  87313. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87314. if (!node) {
  87315. throw new Error(context + ": Failed to find joint " + index);
  87316. }
  87317. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  87318. }
  87319. };
  87320. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  87321. var babylonBone = babylonBones[node.index];
  87322. if (babylonBone) {
  87323. return babylonBone;
  87324. }
  87325. var boneIndex = skin.joints.indexOf(node.index);
  87326. var baseMatrix = BABYLON.Matrix.Identity();
  87327. if (inverseBindMatrixData && boneIndex !== -1) {
  87328. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  87329. baseMatrix.invertToRef(baseMatrix);
  87330. }
  87331. var babylonParentBone = null;
  87332. if (node.parent !== this._rootNode) {
  87333. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  87334. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  87335. }
  87336. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  87337. babylonBones[node.index] = babylonBone;
  87338. return babylonBone;
  87339. };
  87340. GLTFLoader.prototype._getNodeMatrix = function (node) {
  87341. return node.matrix ?
  87342. BABYLON.Matrix.FromArray(node.matrix) :
  87343. 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());
  87344. };
  87345. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  87346. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  87347. var index = indices_1[_i];
  87348. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  87349. if (!node) {
  87350. throw new Error(context + ": Failed to find node " + index);
  87351. }
  87352. this._traverseNode(context, node, action, parentNode);
  87353. }
  87354. };
  87355. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  87356. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  87357. return;
  87358. }
  87359. if (!action(node, parentNode)) {
  87360. return;
  87361. }
  87362. if (node.children) {
  87363. this._traverseNodes(context, node.children, action, node);
  87364. }
  87365. };
  87366. GLTFLoader.prototype._loadAnimations = function () {
  87367. var animations = this._gltf.animations;
  87368. if (!animations) {
  87369. return;
  87370. }
  87371. for (var index = 0; index < animations.length; index++) {
  87372. var animation = animations[index];
  87373. this._loadAnimation("#/animations/" + index, animation);
  87374. }
  87375. };
  87376. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  87377. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  87378. for (var index = 0; index < animation.channels.length; index++) {
  87379. var channel = GLTFLoader._GetProperty(animation.channels, index);
  87380. if (!channel) {
  87381. throw new Error(context + ": Failed to find channel " + index);
  87382. }
  87383. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  87384. if (!sampler) {
  87385. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  87386. }
  87387. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  87388. }
  87389. };
  87390. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  87391. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  87392. if (!targetNode) {
  87393. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  87394. }
  87395. var targetPath;
  87396. var animationType;
  87397. switch (channel.target.path) {
  87398. case "translation": {
  87399. targetPath = "position";
  87400. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87401. break;
  87402. }
  87403. case "rotation": {
  87404. targetPath = "rotationQuaternion";
  87405. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  87406. break;
  87407. }
  87408. case "scale": {
  87409. targetPath = "scaling";
  87410. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87411. break;
  87412. }
  87413. case "weights": {
  87414. targetPath = "influence";
  87415. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  87416. break;
  87417. }
  87418. default: {
  87419. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  87420. }
  87421. }
  87422. var inputData;
  87423. var outputData;
  87424. var checkSuccess = function () {
  87425. if (!inputData || !outputData) {
  87426. return;
  87427. }
  87428. var outputBufferOffset = 0;
  87429. var getNextOutputValue;
  87430. switch (targetPath) {
  87431. case "position": {
  87432. getNextOutputValue = function () {
  87433. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87434. outputBufferOffset += 3;
  87435. return value;
  87436. };
  87437. break;
  87438. }
  87439. case "rotationQuaternion": {
  87440. getNextOutputValue = function () {
  87441. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  87442. outputBufferOffset += 4;
  87443. return value;
  87444. };
  87445. break;
  87446. }
  87447. case "scaling": {
  87448. getNextOutputValue = function () {
  87449. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87450. outputBufferOffset += 3;
  87451. return value;
  87452. };
  87453. break;
  87454. }
  87455. case "influence": {
  87456. getNextOutputValue = function () {
  87457. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  87458. var value = new Array(numTargets);
  87459. for (var i = 0; i < numTargets; i++) {
  87460. value[i] = outputData[outputBufferOffset++];
  87461. }
  87462. return value;
  87463. };
  87464. break;
  87465. }
  87466. }
  87467. sampler.interpolation = sampler.interpolation || "LINEAR";
  87468. var getNextKey;
  87469. switch (sampler.interpolation) {
  87470. case "STEP": {
  87471. getNextKey = function (frameIndex) { return ({
  87472. frame: inputData[frameIndex],
  87473. value: getNextOutputValue(),
  87474. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  87475. }); };
  87476. break;
  87477. }
  87478. case "LINEAR": {
  87479. getNextKey = function (frameIndex) { return ({
  87480. frame: inputData[frameIndex],
  87481. value: getNextOutputValue()
  87482. }); };
  87483. break;
  87484. }
  87485. case "CUBICSPLINE": {
  87486. getNextKey = function (frameIndex) { return ({
  87487. frame: inputData[frameIndex],
  87488. inTangent: getNextOutputValue(),
  87489. value: getNextOutputValue(),
  87490. outTangent: getNextOutputValue()
  87491. }); };
  87492. break;
  87493. }
  87494. default: {
  87495. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  87496. }
  87497. }
  87498. ;
  87499. var keys;
  87500. if (inputData.length === 1) {
  87501. var key = getNextKey(0);
  87502. keys = [
  87503. { frame: key.frame, value: key.value },
  87504. { frame: key.frame + 1, value: key.value }
  87505. ];
  87506. }
  87507. else {
  87508. keys = new Array(inputData.length);
  87509. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  87510. keys[frameIndex] = getNextKey(frameIndex);
  87511. }
  87512. }
  87513. if (targetPath === "influence") {
  87514. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  87515. var _loop_7 = function (targetIndex) {
  87516. var morphTarget = morphTargetManager.getTarget(targetIndex);
  87517. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87518. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87519. babylonAnimation.setKeys(keys.map(function (key) { return ({
  87520. frame: key.frame,
  87521. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  87522. value: key.value[targetIndex],
  87523. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  87524. }); }));
  87525. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  87526. };
  87527. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  87528. _loop_7(targetIndex);
  87529. }
  87530. }
  87531. else {
  87532. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87533. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87534. babylonAnimation.setKeys(keys);
  87535. if (targetNode.babylonAnimationTargets) {
  87536. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  87537. var target = _a[_i];
  87538. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  87539. }
  87540. }
  87541. }
  87542. };
  87543. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  87544. if (!inputAccessor) {
  87545. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  87546. }
  87547. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  87548. inputData = data;
  87549. checkSuccess();
  87550. });
  87551. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  87552. if (!outputAccessor) {
  87553. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  87554. }
  87555. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  87556. outputData = data;
  87557. checkSuccess();
  87558. });
  87559. };
  87560. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  87561. var _this = this;
  87562. this._addPendingData(buffer);
  87563. if (buffer.loadedData) {
  87564. onSuccess(buffer.loadedData);
  87565. this._removePendingData(buffer);
  87566. }
  87567. else if (buffer.loadedObservable) {
  87568. buffer.loadedObservable.add(function (buffer) {
  87569. onSuccess(buffer.loadedData);
  87570. _this._removePendingData(buffer);
  87571. });
  87572. }
  87573. else {
  87574. if (!buffer.uri) {
  87575. throw new Error(context + ": Uri is missing");
  87576. }
  87577. buffer.loadedObservable = new BABYLON.Observable();
  87578. buffer.loadedObservable.add(function (buffer) {
  87579. onSuccess(buffer.loadedData);
  87580. _this._removePendingData(buffer);
  87581. });
  87582. this._loadUriAsync(context, buffer.uri, function (data) {
  87583. buffer.loadedData = data;
  87584. buffer.loadedObservable.notifyObservers(buffer);
  87585. buffer.loadedObservable = undefined;
  87586. });
  87587. }
  87588. };
  87589. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  87590. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  87591. if (!buffer) {
  87592. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  87593. }
  87594. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  87595. var data;
  87596. try {
  87597. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  87598. }
  87599. catch (e) {
  87600. throw new Error(context + ": " + e.message);
  87601. }
  87602. onSuccess(data);
  87603. });
  87604. };
  87605. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  87606. var _this = this;
  87607. if (accessor.sparse) {
  87608. throw new Error(context + ": Sparse accessors are not currently supported");
  87609. }
  87610. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  87611. if (!bufferView) {
  87612. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  87613. }
  87614. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  87615. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  87616. var data;
  87617. var byteOffset = accessor.byteOffset || 0;
  87618. var byteStride = bufferView.byteStride;
  87619. if (byteStride === 0) {
  87620. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  87621. }
  87622. try {
  87623. switch (accessor.componentType) {
  87624. case GLTF2.EComponentType.BYTE: {
  87625. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87626. break;
  87627. }
  87628. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  87629. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87630. break;
  87631. }
  87632. case GLTF2.EComponentType.SHORT: {
  87633. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87634. break;
  87635. }
  87636. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  87637. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87638. break;
  87639. }
  87640. case GLTF2.EComponentType.UNSIGNED_INT: {
  87641. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87642. break;
  87643. }
  87644. case GLTF2.EComponentType.FLOAT: {
  87645. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87646. break;
  87647. }
  87648. default: {
  87649. throw new Error(context + ": Invalid component type " + accessor.componentType);
  87650. }
  87651. }
  87652. }
  87653. catch (e) {
  87654. throw new Error(context + ": " + e);
  87655. }
  87656. onSuccess(data);
  87657. });
  87658. };
  87659. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  87660. byteOffset += data.byteOffset;
  87661. var targetLength = count * numComponents;
  87662. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  87663. return new typedArray(data.buffer, byteOffset, targetLength);
  87664. }
  87665. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  87666. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  87667. var targetBuffer = new typedArray(targetLength);
  87668. var sourceIndex = 0;
  87669. var targetIndex = 0;
  87670. while (targetIndex < targetLength) {
  87671. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  87672. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  87673. targetIndex++;
  87674. }
  87675. sourceIndex += elementStride;
  87676. }
  87677. return targetBuffer;
  87678. };
  87679. GLTFLoader.prototype._addPendingData = function (data) {
  87680. if (!this._renderReady) {
  87681. this._renderPendingCount++;
  87682. }
  87683. this._addLoaderPendingData(data);
  87684. };
  87685. GLTFLoader.prototype._removePendingData = function (data) {
  87686. var _this = this;
  87687. if (!this._renderReady) {
  87688. if (--this._renderPendingCount === 0) {
  87689. this._addLoaderPendingData(this);
  87690. this._compileMaterialsAsync(function () {
  87691. _this._compileShadowGeneratorsAsync(function () {
  87692. _this._removeLoaderPendingData(_this);
  87693. _this._renderReady = true;
  87694. _this._onRenderReady();
  87695. });
  87696. });
  87697. }
  87698. }
  87699. this._removeLoaderPendingData(data);
  87700. };
  87701. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  87702. this._loaderPendingCount++;
  87703. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  87704. var tracker = _a[_i];
  87705. tracker._addPendingData(data);
  87706. }
  87707. };
  87708. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  87709. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  87710. var tracker = _a[_i];
  87711. tracker._removePendingData(data);
  87712. }
  87713. if (--this._loaderPendingCount === 0) {
  87714. this._onComplete();
  87715. }
  87716. };
  87717. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  87718. var _this = this;
  87719. var tracker = new GLTFLoaderTracker(function () {
  87720. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  87721. onComplete();
  87722. });
  87723. this._loaderTrackers.push(tracker);
  87724. this._addLoaderPendingData(tracker);
  87725. action();
  87726. this._removeLoaderPendingData(tracker);
  87727. };
  87728. GLTFLoader.prototype._getDefaultMaterial = function () {
  87729. if (!this._defaultMaterial) {
  87730. var id = "__gltf_default";
  87731. var material = this._babylonScene.getMaterialByName(id);
  87732. if (!material) {
  87733. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  87734. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  87735. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  87736. material.metallic = 1;
  87737. material.roughness = 1;
  87738. }
  87739. this._defaultMaterial = material;
  87740. }
  87741. return this._defaultMaterial;
  87742. };
  87743. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  87744. var babylonMaterial = material.babylonMaterial;
  87745. // Ensure metallic workflow
  87746. babylonMaterial.metallic = 1;
  87747. babylonMaterial.roughness = 1;
  87748. var properties = material.pbrMetallicRoughness;
  87749. if (!properties) {
  87750. return;
  87751. }
  87752. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  87753. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  87754. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  87755. if (properties.baseColorTexture) {
  87756. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  87757. if (!texture) {
  87758. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  87759. }
  87760. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  87761. }
  87762. if (properties.metallicRoughnessTexture) {
  87763. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  87764. if (!texture) {
  87765. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  87766. }
  87767. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  87768. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  87769. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  87770. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  87771. }
  87772. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  87773. };
  87774. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  87775. if (material.babylonMaterial) {
  87776. assign(material.babylonMaterial, false);
  87777. return;
  87778. }
  87779. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  87780. return;
  87781. }
  87782. this._createPbrMaterial(material);
  87783. this._loadMaterialBaseProperties(context, material);
  87784. this._loadMaterialMetallicRoughnessProperties(context, material);
  87785. assign(material.babylonMaterial, true);
  87786. };
  87787. GLTFLoader.prototype._createPbrMaterial = function (material) {
  87788. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  87789. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  87790. material.babylonMaterial = babylonMaterial;
  87791. };
  87792. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  87793. var babylonMaterial = material.babylonMaterial;
  87794. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  87795. if (material.doubleSided) {
  87796. babylonMaterial.backFaceCulling = false;
  87797. babylonMaterial.twoSidedLighting = true;
  87798. }
  87799. if (material.normalTexture) {
  87800. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  87801. if (!texture) {
  87802. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  87803. }
  87804. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  87805. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  87806. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  87807. if (material.normalTexture.scale != null) {
  87808. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  87809. }
  87810. }
  87811. if (material.occlusionTexture) {
  87812. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  87813. if (!texture) {
  87814. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  87815. }
  87816. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  87817. babylonMaterial.useAmbientInGrayScale = true;
  87818. if (material.occlusionTexture.strength != null) {
  87819. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  87820. }
  87821. }
  87822. if (material.emissiveTexture) {
  87823. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  87824. if (!texture) {
  87825. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  87826. }
  87827. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  87828. }
  87829. };
  87830. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  87831. var babylonMaterial = material.babylonMaterial;
  87832. var alphaMode = material.alphaMode || "OPAQUE";
  87833. switch (alphaMode) {
  87834. case "OPAQUE": {
  87835. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  87836. break;
  87837. }
  87838. case "MASK": {
  87839. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  87840. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  87841. if (colorFactor) {
  87842. if (colorFactor[3] == 0) {
  87843. babylonMaterial.alphaCutOff = 1;
  87844. }
  87845. else {
  87846. babylonMaterial.alphaCutOff /= colorFactor[3];
  87847. }
  87848. }
  87849. if (babylonMaterial.albedoTexture) {
  87850. babylonMaterial.albedoTexture.hasAlpha = true;
  87851. }
  87852. break;
  87853. }
  87854. case "BLEND": {
  87855. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  87856. if (colorFactor) {
  87857. babylonMaterial.alpha = colorFactor[3];
  87858. }
  87859. if (babylonMaterial.albedoTexture) {
  87860. babylonMaterial.albedoTexture.hasAlpha = true;
  87861. babylonMaterial.useAlphaFromAlbedoTexture = true;
  87862. }
  87863. break;
  87864. }
  87865. default: {
  87866. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  87867. }
  87868. }
  87869. };
  87870. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  87871. var _this = this;
  87872. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  87873. if (!sampler) {
  87874. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  87875. }
  87876. this._loadSampler("#/samplers/" + sampler.index, sampler);
  87877. this._addPendingData(texture);
  87878. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  87879. _this._tryCatchOnError(function () {
  87880. _this._removePendingData(texture);
  87881. });
  87882. }, function (message) {
  87883. _this._tryCatchOnError(function () {
  87884. throw new Error(context + ": " + message);
  87885. });
  87886. });
  87887. if (texture.url) {
  87888. babylonTexture.updateURL(texture.url);
  87889. }
  87890. else if (texture.dataReadyObservable) {
  87891. texture.dataReadyObservable.add(function (texture) {
  87892. babylonTexture.updateURL(texture.url);
  87893. });
  87894. }
  87895. else {
  87896. texture.dataReadyObservable = new BABYLON.Observable();
  87897. texture.dataReadyObservable.add(function (texture) {
  87898. babylonTexture.updateURL(texture.url);
  87899. });
  87900. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  87901. if (!image_1) {
  87902. throw new Error(context + ": Failed to find source " + texture.source);
  87903. }
  87904. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  87905. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  87906. texture.dataReadyObservable.notifyObservers(texture);
  87907. texture.dataReadyObservable = undefined;
  87908. });
  87909. }
  87910. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  87911. babylonTexture.wrapU = sampler.wrapU;
  87912. babylonTexture.wrapV = sampler.wrapV;
  87913. babylonTexture.name = texture.name || "texture" + texture.index;
  87914. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  87915. return babylonTexture;
  87916. };
  87917. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  87918. if (sampler.noMipMaps != undefined) {
  87919. return;
  87920. }
  87921. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  87922. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  87923. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  87924. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  87925. };
  87926. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  87927. if (image.uri) {
  87928. this._loadUriAsync(context, image.uri, onSuccess);
  87929. }
  87930. else {
  87931. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  87932. if (!bufferView) {
  87933. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  87934. }
  87935. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  87936. }
  87937. };
  87938. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  87939. var _this = this;
  87940. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  87941. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  87942. return;
  87943. }
  87944. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  87945. throw new Error(context + ": Uri '" + uri + "' is invalid");
  87946. }
  87947. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  87948. _this._tryCatchOnError(function () {
  87949. onSuccess(new Uint8Array(data));
  87950. });
  87951. }, function (event) {
  87952. _this._tryCatchOnError(function () {
  87953. if (request && !_this._renderReady) {
  87954. request._lengthComputable = event.lengthComputable;
  87955. request._loaded = event.loaded;
  87956. request._total = event.total;
  87957. _this._onProgress();
  87958. }
  87959. });
  87960. }, this._babylonScene.database, true, function (request, exception) {
  87961. _this._tryCatchOnError(function () {
  87962. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  87963. });
  87964. });
  87965. this._requests.push(request);
  87966. };
  87967. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  87968. if (this._disposed) {
  87969. return;
  87970. }
  87971. try {
  87972. handler();
  87973. }
  87974. catch (e) {
  87975. BABYLON.Tools.Error("glTF Loader: " + e.message);
  87976. if (this._errorCallback) {
  87977. this._errorCallback(e.message, e);
  87978. }
  87979. this.dispose();
  87980. }
  87981. };
  87982. GLTFLoader._AssignIndices = function (array) {
  87983. if (array) {
  87984. for (var index = 0; index < array.length; index++) {
  87985. array[index].index = index;
  87986. }
  87987. }
  87988. };
  87989. GLTFLoader._GetProperty = function (array, index) {
  87990. if (!array || index == undefined || !array[index]) {
  87991. return null;
  87992. }
  87993. return array[index];
  87994. };
  87995. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  87996. // Set defaults if undefined
  87997. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  87998. switch (mode) {
  87999. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  88000. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  88001. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  88002. default:
  88003. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  88004. return BABYLON.Texture.WRAP_ADDRESSMODE;
  88005. }
  88006. };
  88007. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  88008. // Set defaults if undefined
  88009. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  88010. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  88011. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  88012. switch (minFilter) {
  88013. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  88014. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  88015. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  88016. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  88017. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  88018. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  88019. default:
  88020. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  88021. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  88022. }
  88023. }
  88024. else {
  88025. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  88026. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  88027. }
  88028. switch (minFilter) {
  88029. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  88030. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  88031. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  88032. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  88033. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  88034. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  88035. default:
  88036. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  88037. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  88038. }
  88039. }
  88040. };
  88041. GLTFLoader._GetNumComponents = function (context, type) {
  88042. switch (type) {
  88043. case "SCALAR": return 1;
  88044. case "VEC2": return 2;
  88045. case "VEC3": return 3;
  88046. case "VEC4": return 4;
  88047. case "MAT2": return 4;
  88048. case "MAT3": return 9;
  88049. case "MAT4": return 16;
  88050. }
  88051. throw new Error(context + ": Invalid type " + type);
  88052. };
  88053. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  88054. var _this = this;
  88055. if (this.useClipPlane) {
  88056. babylonMaterial.forceCompilation(babylonMesh, function () {
  88057. babylonMaterial.forceCompilation(babylonMesh, function () {
  88058. _this._tryCatchOnError(onSuccess);
  88059. }, { clipPlane: true });
  88060. });
  88061. }
  88062. else {
  88063. babylonMaterial.forceCompilation(babylonMesh, function () {
  88064. _this._tryCatchOnError(onSuccess);
  88065. });
  88066. }
  88067. };
  88068. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  88069. if (!this.compileMaterials || !this._gltf.materials) {
  88070. onSuccess();
  88071. return;
  88072. }
  88073. var meshes = this._getMeshes();
  88074. var remaining = 0;
  88075. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  88076. var mesh = meshes_1[_i];
  88077. if (mesh.material instanceof BABYLON.MultiMaterial) {
  88078. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  88079. var subMaterial = _b[_a];
  88080. if (subMaterial) {
  88081. remaining++;
  88082. }
  88083. }
  88084. }
  88085. else if (mesh.material) {
  88086. remaining++;
  88087. }
  88088. }
  88089. if (remaining === 0) {
  88090. onSuccess();
  88091. return;
  88092. }
  88093. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  88094. var mesh = meshes_2[_c];
  88095. if (mesh.material instanceof BABYLON.MultiMaterial) {
  88096. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  88097. var subMaterial = _e[_d];
  88098. if (subMaterial) {
  88099. this._compileMaterialAsync(subMaterial, mesh, function () {
  88100. if (--remaining === 0) {
  88101. onSuccess();
  88102. }
  88103. });
  88104. }
  88105. }
  88106. }
  88107. else if (mesh.material) {
  88108. this._compileMaterialAsync(mesh.material, mesh, function () {
  88109. if (--remaining === 0) {
  88110. onSuccess();
  88111. }
  88112. });
  88113. }
  88114. }
  88115. };
  88116. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  88117. var _this = this;
  88118. if (!this.compileShadowGenerators) {
  88119. onSuccess();
  88120. return;
  88121. }
  88122. var lights = this._babylonScene.lights;
  88123. var remaining = 0;
  88124. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  88125. var light = lights_1[_i];
  88126. var generator = light.getShadowGenerator();
  88127. if (generator) {
  88128. remaining++;
  88129. }
  88130. }
  88131. if (remaining === 0) {
  88132. onSuccess();
  88133. return;
  88134. }
  88135. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  88136. var light = lights_2[_a];
  88137. var generator = light.getShadowGenerator();
  88138. if (generator) {
  88139. generator.forceCompilation(function () {
  88140. if (--remaining === 0) {
  88141. _this._tryCatchOnError(onSuccess);
  88142. }
  88143. });
  88144. }
  88145. }
  88146. };
  88147. GLTFLoader.prototype._abortRequests = function () {
  88148. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  88149. var request = _a[_i];
  88150. request.abort();
  88151. }
  88152. this._requests.length = 0;
  88153. };
  88154. GLTFLoader.prototype._releaseResources = function () {
  88155. if (this._gltf.textures) {
  88156. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  88157. var texture = _a[_i];
  88158. if (texture.url) {
  88159. URL.revokeObjectURL(texture.url);
  88160. texture.url = undefined;
  88161. }
  88162. }
  88163. }
  88164. };
  88165. GLTFLoader.Extensions = {};
  88166. return GLTFLoader;
  88167. }());
  88168. GLTF2.GLTFLoader = GLTFLoader;
  88169. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  88170. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88171. })(BABYLON || (BABYLON = {}));
  88172. //# sourceMappingURL=babylon.glTFLoader.js.map
  88173. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88174. var BABYLON;
  88175. (function (BABYLON) {
  88176. var GLTF2;
  88177. (function (GLTF2) {
  88178. /**
  88179. * Utils functions for GLTF
  88180. */
  88181. var GLTFUtils = /** @class */ (function () {
  88182. function GLTFUtils() {
  88183. }
  88184. /**
  88185. * If the uri is a base64 string
  88186. * @param uri: the uri to test
  88187. */
  88188. GLTFUtils.IsBase64 = function (uri) {
  88189. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  88190. };
  88191. /**
  88192. * Decode the base64 uri
  88193. * @param uri: the uri to decode
  88194. */
  88195. GLTFUtils.DecodeBase64 = function (uri) {
  88196. var decodedString = atob(uri.split(",")[1]);
  88197. var bufferLength = decodedString.length;
  88198. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  88199. for (var i = 0; i < bufferLength; i++) {
  88200. bufferView[i] = decodedString.charCodeAt(i);
  88201. }
  88202. return bufferView.buffer;
  88203. };
  88204. GLTFUtils.ValidateUri = function (uri) {
  88205. return (uri.indexOf("..") === -1);
  88206. };
  88207. return GLTFUtils;
  88208. }());
  88209. GLTF2.GLTFUtils = GLTFUtils;
  88210. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88211. })(BABYLON || (BABYLON = {}));
  88212. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  88213. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88214. var BABYLON;
  88215. (function (BABYLON) {
  88216. var GLTF2;
  88217. (function (GLTF2) {
  88218. var GLTFLoaderExtension = /** @class */ (function () {
  88219. function GLTFLoaderExtension() {
  88220. this.enabled = true;
  88221. }
  88222. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  88223. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  88224. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  88225. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  88226. var _this = this;
  88227. if (!property.extensions) {
  88228. return false;
  88229. }
  88230. var extension = property.extensions[this.name];
  88231. if (!extension) {
  88232. return false;
  88233. }
  88234. // Clear out the extension before executing the action to avoid recursing into the same property.
  88235. property.extensions[this.name] = undefined;
  88236. action(context + "extensions/" + this.name, extension, function () {
  88237. // Restore the extension after completing the action.
  88238. property.extensions[_this.name] = extension;
  88239. });
  88240. return true;
  88241. };
  88242. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  88243. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  88244. };
  88245. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  88246. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  88247. };
  88248. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  88249. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  88250. };
  88251. GLTFLoaderExtension._ApplyExtensions = function (action) {
  88252. var extensions = GLTFLoaderExtension._Extensions;
  88253. if (!extensions) {
  88254. return false;
  88255. }
  88256. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  88257. var extension = extensions_1[_i];
  88258. if (extension.enabled && action(extension)) {
  88259. return true;
  88260. }
  88261. }
  88262. return false;
  88263. };
  88264. //
  88265. // Utilities
  88266. //
  88267. GLTFLoaderExtension._Extensions = [];
  88268. return GLTFLoaderExtension;
  88269. }());
  88270. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  88271. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88272. })(BABYLON || (BABYLON = {}));
  88273. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  88274. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  88275. var BABYLON;
  88276. (function (BABYLON) {
  88277. var GLTF2;
  88278. (function (GLTF2) {
  88279. var Extensions;
  88280. (function (Extensions) {
  88281. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  88282. var MSFTLOD = /** @class */ (function (_super) {
  88283. __extends(MSFTLOD, _super);
  88284. function MSFTLOD() {
  88285. var _this = _super !== null && _super.apply(this, arguments) || this;
  88286. /**
  88287. * Specify the minimal delay between LODs in ms (default = 250)
  88288. */
  88289. _this.Delay = 250;
  88290. return _this;
  88291. }
  88292. Object.defineProperty(MSFTLOD.prototype, "name", {
  88293. get: function () {
  88294. return "MSFT_lod";
  88295. },
  88296. enumerable: true,
  88297. configurable: true
  88298. });
  88299. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  88300. return this._loadExtension(context, node, function (context, extension, onComplete) {
  88301. for (var i = extension.ids.length - 1; i >= 0; i--) {
  88302. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  88303. if (!lodNode) {
  88304. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  88305. }
  88306. loader._traverseNode(context, lodNode, action, parentNode);
  88307. }
  88308. loader._traverseNode(context, node, action, parentNode);
  88309. onComplete();
  88310. });
  88311. };
  88312. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  88313. var _this = this;
  88314. return this._loadExtension(context, node, function (context, extension, onComplete) {
  88315. var nodes = [node];
  88316. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  88317. var index = _a[_i];
  88318. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  88319. if (!lodNode) {
  88320. throw new Error(context + ": Failed to find node " + index);
  88321. }
  88322. nodes.push(lodNode);
  88323. }
  88324. loader._addLoaderPendingData(node);
  88325. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  88326. loader._removeLoaderPendingData(node);
  88327. onComplete();
  88328. });
  88329. });
  88330. };
  88331. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  88332. var _this = this;
  88333. loader._whenAction(function () {
  88334. loader._loadNode(context, nodes[index]);
  88335. }, function () {
  88336. if (index !== nodes.length - 1) {
  88337. var previousNode = nodes[index + 1];
  88338. previousNode.babylonMesh.setEnabled(false);
  88339. }
  88340. if (index === 0) {
  88341. onComplete();
  88342. return;
  88343. }
  88344. setTimeout(function () {
  88345. loader._tryCatchOnError(function () {
  88346. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  88347. });
  88348. }, _this.Delay);
  88349. });
  88350. };
  88351. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  88352. var _this = this;
  88353. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88354. var materials = [material];
  88355. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  88356. var index = _a[_i];
  88357. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  88358. if (!lodMaterial) {
  88359. throw new Error(context + ": Failed to find material " + index);
  88360. }
  88361. materials.push(lodMaterial);
  88362. }
  88363. loader._addLoaderPendingData(material);
  88364. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  88365. loader._removeLoaderPendingData(material);
  88366. onComplete();
  88367. });
  88368. });
  88369. };
  88370. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  88371. var _this = this;
  88372. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  88373. if (index === materials.length - 1) {
  88374. assign(babylonMaterial, isNew);
  88375. // Load the next LOD when the loader is ready to render.
  88376. loader._executeWhenRenderReady(function () {
  88377. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88378. });
  88379. }
  88380. else {
  88381. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  88382. assign(babylonMaterial, isNew);
  88383. if (index === 0) {
  88384. onComplete();
  88385. }
  88386. else {
  88387. setTimeout(function () {
  88388. loader._tryCatchOnError(function () {
  88389. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88390. });
  88391. }, _this.Delay);
  88392. }
  88393. });
  88394. }
  88395. });
  88396. };
  88397. return MSFTLOD;
  88398. }(GLTF2.GLTFLoaderExtension));
  88399. Extensions.MSFTLOD = MSFTLOD;
  88400. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  88401. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88402. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88403. })(BABYLON || (BABYLON = {}));
  88404. //# sourceMappingURL=MSFT_lod.js.map
  88405. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  88406. var BABYLON;
  88407. (function (BABYLON) {
  88408. var GLTF2;
  88409. (function (GLTF2) {
  88410. var Extensions;
  88411. (function (Extensions) {
  88412. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  88413. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  88414. function KHRMaterialsPbrSpecularGlossiness() {
  88415. return _super !== null && _super.apply(this, arguments) || this;
  88416. }
  88417. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  88418. get: function () {
  88419. return "KHR_materials_pbrSpecularGlossiness";
  88420. },
  88421. enumerable: true,
  88422. configurable: true
  88423. });
  88424. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  88425. var _this = this;
  88426. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88427. loader._createPbrMaterial(material);
  88428. loader._loadMaterialBaseProperties(context, material);
  88429. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  88430. assign(material.babylonMaterial, true);
  88431. onComplete();
  88432. });
  88433. };
  88434. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  88435. var babylonMaterial = material.babylonMaterial;
  88436. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  88437. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  88438. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  88439. if (properties.diffuseTexture) {
  88440. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  88441. if (!texture) {
  88442. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  88443. }
  88444. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  88445. }
  88446. if (properties.specularGlossinessTexture) {
  88447. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  88448. if (!texture) {
  88449. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  88450. }
  88451. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  88452. babylonMaterial.reflectivityTexture.hasAlpha = true;
  88453. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  88454. }
  88455. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  88456. };
  88457. return KHRMaterialsPbrSpecularGlossiness;
  88458. }(GLTF2.GLTFLoaderExtension));
  88459. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  88460. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  88461. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88462. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88463. })(BABYLON || (BABYLON = {}));
  88464. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  88465. (function universalModuleDefinition(root, factory) {
  88466. var f = factory();
  88467. if (root && root["BABYLON"]) {
  88468. return;
  88469. }
  88470. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  88471. globalObject["BABYLON"] = f;
  88472. if(typeof exports === 'object' && typeof module === 'object')
  88473. module.exports = f;
  88474. else if(typeof define === 'function' && define.amd)
  88475. define(["BABYLON"], factory);
  88476. else if(typeof exports === 'object')
  88477. exports["BABYLON"] = f;
  88478. else {
  88479. root["BABYLON"] = f;
  88480. }
  88481. })(this, function() {
  88482. return BABYLON;
  88483. });